我有一些PHP代码调用,然后从API(使用file_get_contents()
)接收响应,API响应的XML格式如下:
<?xml version="1.0"?>
<root><status>success</status>
<duration>5 seconds</duration>
<average>13692.4</average></root>
例如,在PHP中,我如何获取这个XML响应并获得(比方说)<average>
的值?如有任何帮助,我们将不胜感激:)
解析XML有几种方法,其中之一就是XMLReader。从您发布的XML中检索average
值的一个简单示例如下:
<?php
// Read the XML output from the API
$xml = file_get_contents('https://api.example.com/output.xml');
$reader = new XMLReader();
$reader->open('data://text/xml,' . $xml);
// Read the XML
while ($reader->read()) {
// Look for the "average" node
if ($reader->name == 'average') {
$value = $reader->readString();
if (!empty($value)) {
// This will output 13692.4
var_dump($value);
}
}
}
$reader->close();
这里可以看到一个活生生的例子:https://3v4l.org/s7sNl