SimpleXML: Get value where attribute is variable [duplicate]

做~自己de王妃 提交于 2019-12-06 08:20:29

问题


<path>
    <name>
        <option id="6523">
            <needle>Haystack</needle>
            <foo>bar</foo>
        </option>

        <option id="6524">
            <needle>Haystack</needle>
            <foo>Bar</foo>
        </option>
    </name>
</path>

Hello again Stackoverflow!

For example, i want the Needle and the foo from option 6524, how do i get those using SimpleXML? I've tried xpath (almoast every topic here on stackoverflow suggests xpath) but that didn't work out for me! Can you guys help me?

Thanks!


回答1:


Try this code:

$xml_str = '.....';

$xml = simplexml_load_string($xml_str);
$result = $xml->xpath('//name/option[@id="6524"]/foo');

echo $result[0][0];    

On Codepad.org




回答2:


Use xpath:

<?php
$xml = <<<XML
<path>
    <name>
        <option id="6523">
            <needle>Haystack</needle>
            <foo>bar</foo>
        </option>

        <option id="6524">
            <needle>Haystack</needle>
            <foo>Bar</foo>
        </option>
    </name>
</path>
XML;

$xml = new SimpleXMLElement($xml);
$options = $xml->xpath('//option[@id = "6524"]');
$opt = $options[0];

echo 'needle: ' . $opt->needle . ', foo: ' . $opt->foo;



回答3:


Try something like this:

$xml = simplexml_load_string($string);
$result = $xml->xpath('/path/name/option');
while(list( , $node) = each($result)) {
    echo $node->needle . " - " . $node->foo . "<br />";
}



回答4:


Try this:

$result = $xml->xpath('//path/name/option[@id="6524"]');



来源:https://stackoverflow.com/questions/8105480/simplexml-get-value-where-attribute-is-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!