Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用simplexml为字段值解析PHP_Php_Xml Parsing_Simplexml - Fatal编程技术网

使用simplexml为字段值解析PHP

使用simplexml为字段值解析PHP,php,xml-parsing,simplexml,Php,Xml Parsing,Simplexml,正在尝试分析以下xml: <?xml version="1.0"?> <devices> <device name="TEMP" index="0" available="1" type="" id="xxx"> <field type="2" max="50" min="-20&quo

正在尝试分析以下xml:

<?xml version="1.0"?>
<devices>
<device name="TEMP" index="0" available="1" type="" id="xxx">
<field type="2" max="50" min="-20" niceName="Temperature (C)" value="24.75" key="TempC"/>
<field type="2" max="122" min="-4" niceName="Temperature (F)" value="76.55" key="TempF"/>

然后将TempF值拉到76.55

这是我尝试的代码,但我没有做一些不对的事情:

$xml = simplexml_load_file('c:\data.xml') or die("Error: Cannot create object");
echo '<h2>Server Temperature</h2>';
$list = $xml->devices;
for ($i = 0; $i < count($list); $i++) {
    echo 'Temp: ' .$list[$i]->TempF[value] . '<br>';
$xml=simplexml\u加载文件('c:\data.xml')或死(“错误:无法创建对象”);
回声“服务器温度”;
$list=$xml->devices;
对于($i=0;$iTempF[value]。

您可以循环
$devices->device
,而无需使用for循环

echo '<h2>Server Temperature</h2>';
foreach ($xml->device as $device) {
    foreach ($device->field as $field) {
        $att = $field->attributes();
        if ((string)$att->key === "TempF") {
            echo 'Temp: ' . $field->attributes()->value . "<br>";
        }
    }
}
echo“服务器温度”;
foreach($xml->device as$device){
foreach($device->field作为$field){
$att=$field->attributes();
如果((字符串)$att->key==“TempF”){
回显“Temp:”.$field->attributes()->value。“
”; } } }
输出

<h2>Server Temperature</h2>Temp: 76.55<br>
<h2>Server Temperature</h2>Temp: 76.55<br>
Server TemperatureTemp:76.55

或者,如果要循环字段的所有值,可以使用xpath:

echo '<h2>Server Temperature</h2>';
foreach ($xml->xpath('/devices/device/field[@key="TempF"]/@value') as $value) {
    echo 'Temp: ' . $value . "<br>";
}
echo“服务器温度”;
foreach($xml->xpath('/devices/device/field[@key=“TempF”]/@value')作为$value){
回显“温度:”.$value.“
”; }
输出

<h2>Server Temperature</h2>Temp: 76.55<br>
<h2>Server Temperature</h2>Temp: 76.55<br>
Server TemperatureTemp:76.55

请参阅另一个

谢谢!但该代码似乎仍然没有显示数据,只是获取h2文本。@jackstrum请参阅
Temp:76.55
其中
76.55
来自xml@jackstrum看,我在答案中添加了2个演示。明白了,谢谢!!