1
votes

I searched SO and found some answeres

xpath-how-to-select-a-node-by-its-attribute

simplexml-get-element-content-based-on-attribute-value

and

simplexml-selecting-elements-which-have-a-certain-attribute-value

but they all not helped me with my problem. May the problem was similar but it wasnt the same so it did not solved anything.

As you can see in the title I want to select the content of a specific node.

First, here a sample XML thats similar to the XML I'm using:

<?xml version="1.0" encoding="utf-8"?>
<translation>
    <home>
        <button name="aaa">Hello</button>
        <button name="bbb">World</button>
    </home>
    <office>
        <button name="ccc">Foo</button>
        <button name="ddd">Bar</button>
        <string name="xxx">Sample</string>
    </office>
<translation>

So what I actually want to achive is to use my xml select like php assoc arrays. Something like this:

$xml->home->button["aaa"];

or may more xpath like:

$xml->home->button['@name="aaa"'];

both should return Hello but everything I'm trying ends up with a object of the attribute (missing the content at all) or an empty return.

I tried:

$xml = simplexml_load_file( "my.xml" );

//1)
$data = $xml->xpath('//home[button[@name="aaa"]]');
//what simply gives me an array of all buttons and they can be accessed by its id

//2)
$data = $xml->xpath('//home/button[@name="aaa"]');
//what gives me the expacted node but not the content and even the
//print_r or var_dump doesnt show me the content anymore

I tried a view more things that actually all end up with no result.

What can I do to achive my goal ?

1

1 Answers

1
votes

This outputs the expected Hello for me :

$string = <<<XML
<translation>
    <home>
        <button name="aaa">Hello</button>
        <button name="bbb">World</button>
    </home>
    <office>
        <button name="ccc">Foo</button>
        <button name="ddd">Bar</button>
        <string name="xxx">Sample</string>
    </office>
</translation>
XML;
$xml = new SimpleXMLElement($string);
$data = $xml->xpath("//home/button[@name='aaa']")[0];
echo $data;

eval.in demo