views:

537

answers:

2

Hey everybody,

I have a question about xpath and arrays. What I was wondering was if it is possible to use xpath on some simpleXML and have it return an associative array of node names and their values. For example, say I have the following XML:

<element1 page="1">blah</element1>
<element2 page="1">blah blah</element2>
<element3 page="2">blah</element3>
<element4 page="3">blah blah</element4>

Now if I were to go $xml->xpath('//node()[@page="1"]'); then it would return an array like the following:

array( 0 => 'blah' , 1 => 'blah blah' );

Is it possible to get an array similar to the one below?

array( element1 => 'blah' , element2 => 'blah blah' );

Thanks for the help!

+1  A: 

I don't think you can fetch that into that kind of array (you would need to tell PHP what tags, child nodes, attributes, etc to put there), but you can fetch DOMNode elements using the DOMXPath class, which gives you a DOMNodeList object:

$document = new DOMDocument();
$document->load($myXmlFile);
$xpath = new DOMXPath($document);

$result = $xpath->query('//node()[@page="1"]');
var_dump($result->length); // int(2)
var_dump($result->item(0)->tagName); // string(8) "element1"
var_dump($result->item(1)->tagName); // string(8) "element2"
soulmerge
A: 

For simple XML the array is not exactly as you mentioned it's more like:

$result = array( 0 => simplexmlObject('blah') , 1 => simplexmlObject('blah blah') );

because you have a SimpleXML object and not a literal string you still have access to the full SimpleXML document:

$result[0]->addChild("another", "child");

// which is <element1 page="1">blah<another>child</another></element1>

or closer to your question

$name = $result[0]->getName();

and if you are smitten with all the things you can do with DOM properties then you can do something like:

$parent = dom_import_simplexml($result[0])->parent;
null