PHP SimpleXML Xpath

Hi Folks,

I’ve come across a strange quirk and was wondering if anyone had any ideas:

Consider the following:

<?xml version = “1.0” encoding = “UTF-8”?>
<websites>
<website1>
<url>someting.com</url>
</website1>
<website2>
<url>someting2.com</url>
</website2>
<website3>
<url>someting3.com</url>
</website3>
<website4>
<url>someting4.com</url>
</website4>
</websites>

Using

$website = @simplexml_load_string($xml);

foreach ($websites as $website) {

$url = $website->xpath(‘//url’);

print_r($new);

}

I would expect $new to be an array with just one entry but instead contains all four url nodes.

Is this just how xpath works with simplexml?

Cheers,

DV

The // tells xpath to look throughout the document, not within the current node.e

Try:

$url = website->xpath('/url');

instead.

$website = @simplexml_load_string($xml);

foreach ($websites

vars are named differently.

Sorry, it should be

$websites = @simplexml_load_string($xml);

foreach ($websites as $website) {

$url = $website->xpath(‘//url’);

print_r($new);

}

Thanks for the replies

Using “.” to select the current node can also be useful to make sure you remove any ambiguity:

$url = $website->xpath(‘./ctx:context-object/ctx:referent/ctx:metadata-by-val/ctx:metadata’);