Hannes Meyer
Hannes Meyer

Reputation: 11

XPath and PHP: nothing works properly

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?

Upvotes: 1

Views: 225

Answers (2)

GreenRover
GreenRover

Reputation: 1516

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);

Upvotes: 0

Andrew Cheong
Andrew Cheong

Reputation: 30273

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

Upvotes: 3

Related Questions