tags:

views:

70

answers:

3

Hey,

I've never really used the dom parser before and now I have a question.

How would I go about extracting the url from this

<files>
<file path="http://www.thesite.com/download/eysjkss.zip" title="File Name" />
</files>

Thanks

+4  A: 

Using simpleXML:

$xml = new SimpleXMLElement($xmlstr);
echo $xml->file['path']."\n";

Output:

http://www.thesite.com/download/eysjkss.zip
Alexandre Jasmin
Just be careful. The value of $xml->file['path'] isn't a string. It's an instance of SimpleXMLElement.
mellowsoon
Indeed. It can cause problems when comparing the value to another string but you can cast this value to a string beforehand `(string)$xml->file['path']`
Alexandre Jasmin
thanks guys, exactly what I was looking for
Belgin Fish
this is not DOM though
Gordon
yeah but it's still an efficient way of doing it that I didn't know about, I still +1'ed your answer.
Belgin Fish
A: 

you can use PHP Simple HTML DOM Parser,this is a php library。http://simplehtmldom.sourceforge.net/

Sam
Why introduce a 3rd party library when the built-in features are more than adequate for this task?
Phil Brown
It is like jquery,Very convenient
Sam
Suggested third party alternatives to [SimpleHtmlDom](http://simplehtmldom.sourceforge.net/) that actually use [DOM](http://php.net/manual/en/book.dom.php) instead of String Parsing: [phpQuery](http://code.google.com/p/phpquery/), [Zend_Dom](http://framework.zend.com/manual/en/zend.dom.html), [QueryPath](http://querypath.org/) and [FluentDom](http://www.fluentdom.org).
Gordon
+1  A: 

To do it with DOM you do

$dom = new DOMDocument;
$dom->load( 'file.xml' );
foreach( $dom->getElementsByTagName( 'file' ) as $file ) {
    echo $file->getAttribute( 'path' );
}

You can also do it with XPath:

$dom = new DOMDocument;
$dom->load( 'file.xml' );
$xPath = new DOMXPath( $dom );
foreach( $xPath->query( '/files/file/@path' ) as $path ) {
    echo $path->nodeValue;
}

You can fetch individual nodes also by traversing the DOM manually

$dom = new DOMDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->load( 'file.xml' );
echo $dom->documentElement->firstChild->getAttribute( 'path' );

Marking this CW, because this has been answered before multiple times (just with different elements), including me, but I am too lazy to find the duplicate.

Gordon