使用SimpleXML按属性选择一个节点的内容

时间:2015-07-25 04:29:12

标签: php xml xpath

我搜索了SO并发现了一些回答

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

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

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

但他们都没有帮我解决我的问题。问题可能类似,但它不一样,所以它没有解决任何问题。

正如您在标题中看到的,我想选择特定节点的内容。

首先,这里有一个类似于我正在使用的XML的示例XML:

<?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>

所以我真正想要实现的是使用我的xml选择像php assoc数组。 像这样:

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

或者可能更像xpath:

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

两者都应该返回Hello,但我正在尝试的所有内容都会以属性对象(完全没有内容)或空回来结束。

我试过了:

$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

我尝试了一些视图,但实际上所有内容都没有结果。

我能做些什么来实现我的目标?

1 个答案:

答案 0 :(得分:1)

这为我输出了预期的Hello

$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

相关问题