views:

34

answers:

3

Consider the following code :

$dom = new DOMDocument();
$dom->loadXML($file);

$xmlPath = new DOMXPath($dom);
$arrNodes = $xmlPath->query('*/item');
foreach($arrNodes as $item){
//missing code
}

The $file is an xml and each item has a title and a description. How can I display them (title and description)?

$file = "<item>
   <title>test_title</title>
   <desc>test</desc>
</item>";
+2  A: 

I suggest using php's simplexml, with that, you still get xpath functionality, but with easier approach, for example you would access attributes like this:

$name = $item['name'];

Here's an example:

xmlfile.xml:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <items>
        <item title="Hello World" description="Hellowing the world.." />
        <item title="Hello People" description="greeting people.." />
    </items>
</xml>

do.php:

<?php
$xml_str = file_get_contents('xmlfile.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('*/item');

foreach($items as $item) {
    echo $item['title'], ': ', $item['description'], "\n";
}
aularon
Ok , but is xpath that limited ?
I edited adding an example if you wanna check and test.
aularon
@daniphp, how do you mean, are you asking about xpath query capabilities in general or about simplexml's limitations?
aularon
+1  A: 

If your item looks like this:

<item>
    <title>foo</title>
    <description>frob</description>    
</item>

You could use getElementsByTagName() and nodeValue:

foreach($arrNodes as $item){
    print $item->getElementsByTagName('title')->item(0)->nodeValue;
}

Are title and description attributes? E. g. does an item look like this:

<item title="foo" description="frob" />

If so, you could just use getAttribute():

...
foreach($arrNodes as $item){
    print $item->getAttribute('title');
}
Max
They are nodes.
A: 

The right XPath expression should be:

/*/item/title | /*/item/desc

Or

/*/item/*[self::title or self::desc]

This is evaluate to a node set with title and desc element in document order

Alejandro