D
D
Darth Vader2015-11-14 13:38:18
PHP
Darth Vader, 2015-11-14 13:38:18

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>

I need to collect this data 323.777331
I do this
$xmlstring=file_get_contents("ссылка на xml файл");
        $xml = simplexml_load_string($xmlstring);
        $res=$xml->xpath("//Item[@FirstCode='USD']");
        var_dump($res);

But why does not work and sends me
array(0) { }
How to solve this problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2015-11-15
@glebovgin

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

If this obviously working code does not work, then you need to check whether the xpath module is connected.

A
Alexander Taratin, 2015-11-14
@Taraflex

How to get data from xml using php?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question