Answer the question
In order to leave comments, you need to log in
How to use to select the necessary elements from xml using xpath?
Good day, I have the following XML
<CurrencyRateListAnswer>
<Result>
<Content>
<Item FirstCode="USD" SecondCode="RUB">69.966015</Item>
<Item FirstCode="CNY" SecondCode="KZT">50.799100</Item>
<Item FirstCode="RUB" SecondCode="KZT">4.859019</Item>
<Item FirstCode="USD" SecondCode="KZT">323.777331</Item>
<Item FirstCode="RUB" SecondCode="CNY">0.091096</Item>
<Item FirstCode="USD" SecondCode="CNY">6.070173</Item>
</Content>
</Result>
</CurrencyRateListAnswer>
$xmlstring=file_get_contents("ссылка на xml файл");
$xml = simplexml_load_string($xmlstring);
$res=$xml->xpath("//Item[@FirstCode='USD']");
var_dump($res);
array(0) { }
Answer the question
In order to leave comments, you need to log in
The example you specified is working, though I used simple_load_string, but this doesn’t really change the essence. The output will be an array of three elements, because with the FirstCode="USD" attribute in your xml there are 3 elements. I would suggest using the more classic xpath way:
$xml = '<CurrencyRateListAnswer>
<Result>
<Content>
<Item FirstCode="USD" SecondCode="RUB">69.966015</Item>
<Item FirstCode="CNY" SecondCode="KZT">50.799100</Item>
<Item FirstCode="RUB" SecondCode="KZT">4.859019</Item>
<Item FirstCode="USD" SecondCode="KZT">323.777331</Item>
<Item FirstCode="RUB" SecondCode="CNY">0.091096</Item>
<Item FirstCode="USD" SecondCode="CNY">6.070173</Item>
</Content>
</Result>
</CurrencyRateListAnswer>';
$dom = new DOMDocument('UTF-8');
$dom->preserveWhiteSpace = false;
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$query = $xpath->query('//Item[@FirstCode="USD" and @SecondCode="KZT"]');
echo $query->item(0)->nodeValue; // 323.777331
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question