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

Thew
  • 15,789
  • 18
  • 59
  • 100

4 Answers4

2

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

ComFreek
  • 29,044
  • 18
  • 104
  • 156
0

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;
phihag
  • 278,196
  • 72
  • 453
  • 469
0

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 />";
}
Niels
  • 48,601
  • 4
  • 62
  • 81
0

Try this:

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

lgomezma
  • 1,597
  • 2
  • 15
  • 30