1

Here is my code:

$XML = <<<XML
<items>
    <item id="123">
        <name>Item 1</name>
    </item>
    <item id="456">
        <name>Item 2</name>
    </item>
    <item id="789">
        <name>Item 3</name>
    </item>
</items>
XML;


$objSimpleXML = new SimpleXMLElement($XML);

print_r($objSimpleXML->xpath('./item[1]'));
print "- - - - - - -\n";
print_r($objSimpleXML->xpath('./item[2][@id]'));
print "- - - - - - -\n";
print_r($objSimpleXML->xpath('./item[1]/name'));

Nothing really special: I am trying to extract some data via XPath. The path must be a string to design a dynamic program which loads its data from a XML configuration file.

When using PHP object access like $objSimpleXML->items->item[0]['id'] everything works fine. But XPath approach does not really work. The code above generates the following output:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => 123
                )

            [name] => Item 1
        )

)
- - - - - - -
Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => 456
                )

            [name] => Item 2
        )

)
- - - - - - -
Array
(
    [0] => SimpleXMLElement Object
        (
        )

)

I agree with the first output. But in the second output the whole element is returned instead of the attribute. Why? And the last listing is empty instead of name content?

Roland Keesom
  • 8,180
  • 5
  • 45
  • 52

2 Answers2

3

It's because your XPath is wrong. You're using predicates, i.e.

./item[2][@id]

which means "the second item that has an id attribute", but it appears you want

./item[2]/@id
Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
0

try this, if that is not what you are looking for, please give a better example.

<?php

$XML = <<<XML
<items>
    <item id="123">
        <name>Item 1</name>
    </item>
    <item id="456">
        <name>Item 2</name>
    </item>
    <item id="789">
        <name>Item 3</name>
    </item>
</items>
XML;


$objSimpleXML = new SimpleXMLElement($XML);

$items = $objSimpleXML->xpath('./item');

print '<pre>';
print_r($items[0]);
print "- - - - - - -\n";
print_r($items[1]->attributes()->id);
print "- - - - - - -\n";
print_r($items[2]->name);
GreenRover
  • 1,486
  • 1
  • 14
  • 33