Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a node attribute from XML using PHP's DOM Parser

Tags:

dom

php

xml

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 markup:

<files>
    <file path="http://www.thesite.com/download/eysjkss.zip" title="File Name" />
</files>
like image 327
Belgin Fish Avatar asked Oct 22 '10 01:10

Belgin Fish


2 Answers

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->evaluate( '/files/file/@path' ) as $path ) {
    echo $path->nodeValue;
}

Or as a string value directly:

$dom = new DOMDocument;
$dom->load( 'file.xml' );
$xPath = new DOMXPath( $dom );
echo $xPath->evaluate( 'string(/files/file/@path)' );

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.

like image 90
3 revs, 2 users 85% Avatar answered Oct 18 '22 03:10

3 revs, 2 users 85%


Using simpleXML:

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

Output:

http://www.thesite.com/download/eysjkss.zip
like image 26
Alex Jasmin Avatar answered Oct 18 '22 03:10

Alex Jasmin