Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleXML: Get value where attribute is variable [duplicate]

Tags:

php

xml

simplexml

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

like image 603
Thew Avatar asked Apr 07 '26 09:04

Thew


1 Answers

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

like image 133
ComFreek Avatar answered Apr 09 '26 22:04

ComFreek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!