9

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>

3 Answers 3

13

Using simpleXML:

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

Output:

http://www.thesite.com/download/eysjkss.zip
Sign up to request clarification or add additional context in comments.

3 Comments

Just be careful. The value of $xml->file['path'] isn't a string. It's an instance of SimpleXMLElement.
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']
yeah but it's still an efficient way of doing it that I didn't know about, I still +1'ed your answer.
12

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.

Comments

-1

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

3 Comments

Why introduce a 3rd party library when the built-in features are more than adequate for this task?
It is like jquery,Very convenient
Suggested third party alternatives to SimpleHtmlDom that actually use DOM instead of String Parsing: phpQuery, Zend_Dom, QueryPath and FluentDom.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.