【问题标题】:Use SimpleXML to select content of one node by its attribute使用 SimpleXML 通过其属性选择一个节点的内容
【发布时间】:2015-07-25 13:32:43
【问题描述】:

我搜了一下,找到了一些答案

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

我尝试查看更多实际上都没有结果的事情。

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

【问题讨论】:

    标签: php xml xpath


    【解决方案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

    【讨论】:

    • omg,花了这么多时间,最后它是一个简单的[0],它可以解决所有问题...... grrrrr :D 非常感谢。我会尽快接受这个。
    猜你喜欢
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2010-12-31
    相关资源
    最近更新 更多