gpt4 book ai didi

php - 帮助在php中访问xml属性

转载 作者:行者123 更新时间:2023-12-01 20:02:57 24 4
gpt4 key购买 nike

我对 php 和一般编码很陌生。我正在尝试从远程设备解析 xml 并访问特定值数据。例如,我想显示第 9 组探头 1 的值,但我无法让它工作。有什么建议吗?

这是 xml:

<?xml version="1.0" encoding="ISO-8859-1" ?> 
- <Device id="S10011" hb="1935">
<Group id="1" />
<Group id="2" />
<Group id="3" />
<Group id="4" />
<Group id="5" />
<Group id="6" />
<Group id="7" />
<Group id="8" />
- <Group id="9">
- <Probe id="99">
<Value>1.0</Value>
</Probe>
- <Probe id="1">
<Value>86.4</Value>
</Probe>
- <Probe id="2">
<Value>45.7</Value>
</Probe>
- <Probe id="3">
<Value>2.9</Value>
</Probe>
- <Probe id="4">
<Value>1.0</Value>
</Probe>
</Group>
</Device>
<小时/>

这是我在 xml 中读取的 php 代码:

    <?php
// Establish a port 80 connection
$http = fsockopen("192.168.2.106",80);

// Send a request to the server
$req = "GET /xmldata HTTP/1.0\r\n";
$req .= "Host: 192.168.2.106\r\n";
$req .= "Connection: Close\r\n\r\n";
fputs($http, $req);

// Output the request results
while(!feof($http)) {
$xmlstr .= fgets($http, 2048);
}
// Close the connection
fclose($http);


$xml = simplexml_load_string($xmlstr);

print_r($xml);

$myValue = $xml->xpath('//Group[@ID="9"]/Probe[@ID="1"]/value');
echo $myValue;
?>

A print_r($xml);显示以下信息:

    SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => S10011
[hb] => 158221
)

[Group] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 1
)

[0] =>

)

[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 2
)

[0] =>

)

[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 3
)

[0] =>

)

[3] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 4
)

[0] =>

)

[4] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 5
)

[0] =>

)

[5] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 6
)

[0] =>

)

[6] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 7
)

[0] =>

)

[7] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 8
)

[0] =>

)

[8] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 9
)

[Probe] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 99
)

[Value] => 2.0
)

[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 1
)

[Value] => 89.6
)

[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 2
)

[Value] => 42.7
)

[3] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 3
)

[Value] => 3.9
)

[4] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 4
)

[Value] => 1.0
)

)

)

)

)

最佳答案

试试这个:

   $myValue = $xml->xpath('//Group[@id="9"]/Probe[@id="1"]/Value');  
echo $myValue[0];

关于php - 帮助在php中访问xml属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3400288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com