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>
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.
Using simpleXML:
$xml = new SimpleXMLElement($xmlstr);
echo $xml->file['path']."\n";
Output:
http://www.thesite.com/download/eysjkss.zip
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With