Parse a XML and search a string in it

Hi.

If I have a XML like this one:

<root>
<page url="/index.php" title="Page Title"/>
<page url="/page2.php" title="Page Title 2"/>
<page url="/page3.php" title="Page Title 3"/>
</root>

How do I get the node for a given URL?

I need to do a search using the url attribute value.

Thanks…

[FPHP]SimpleXML[/FPHP] with xpath?

How do I do it?

I’ve looking around but haven’t find an example.

http://www.w3schools.com/xpath/xpath_syntax.asp

Combined with the example on the xpath manual page in the PHP manual (linked above), you should be able to put together what you need…

I’ll help out, sometimes it’s hard to grok this stuff without an example with some personal relevance. :slight_smile:


<?php
$strXml = '<root>
    <page url="/index.php" title="Page Title" />
    <page url="/page2.php" title="Page Title 2" />
    <page url="/page3.php" title="Page Title 3" />
</root>';


$objXml = new SimpleXMLElement($strXml);


$page = array_shift($objXml->xpath('page[@url="/page2.php"]'));


echo $page['title'];

Great, thanks!

What if I don’t know the node’s name?

I’ll leave that to you, a well crafted Google search should do the trick. :wink:

I’ve been looking for 2 days now, no luck :blush: :headbang:

What have you tried so far?

The only thing I’ve tried is look for an example of something at least close to what I need :injured:

See “Select Unknown Nodes”

http://www.w3schools.com/xpath/xpath_syntax.asp

I got it. Thanks!

<?php
$strXml = '<root>
    <page url="/index.php" title="Page Title" />
    <page url="/page2.php" title="Page Title 2" />
    <page url="/page3.php" title="Page Title 3" />
</root>';


$objXml = new SimpleXMLElement($strXml);


$page = array_shift($objXml->xpath('//*[@url="/page2.php"]'));

echo $page['title'];
?>

Perfect! Well done. :slight_smile:

[ot]Pleeeeaaaaasssseeeee don’t use array_shift() there, it is intended to manipulate an array variable and when not used on one (as above) you’ll get an E_STRICT message (Strict Standards: Only variables should be passed by reference in X on line X) each and every time it is used.

There is nothing wrong with accessing the element(s) in the array with normal array offset syntax ($page[0]), a loop (foreach ($page as $p)…) or if you really must, some other function which gets the item from the array without expecting an array variable.

It might also be nice to try and get at the title directly, which isn’t so “simple” with SimpleXML but is with DOM.

$doc = new DOMDocument;
$doc->loadXML($strXml);
$xpath = new DOMXPath($doc);
echo $xpath->evaluate('string(*[@url="/page2.php"]/@title)');

[/ot]