我是PHP编程的新手,需要帮助。我有一个变量$ output,它存储从服务器收到的XML响应。如何将“值”数据分配给变量。例如,$ devicesn =“db00-0030-6602-xxxx”。 Bellow是我在回显$ output变量并在浏览器上使用“view source”时得到的XML响应。
Map
答案 0 :(得分:0)
最好的方法是使用simplexml_load_string的xml,然后将其用作对象。
<?php
$xml=simplexml_load_string($output)
$devicesn = $xml-> GetDeviceInfo[0]-> DeviceSn;
echo $devicesn;
?>
答案 1 :(得分:0)
SimpleXML使PHP中的XML处理非常简单(假设您不需要所有的装饰等),此示例加载已检索的内容,然后为输入中的每个设备执行foreach
。然后,对于每个设备,它使用XPath检索一些细节(在name
中查找带有正确标记的详细信息)
<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$xmlText =<<<XML
<?xml version="1.0" encoding="utf-8"?>
<simsrv version="1.0" msg_type="response">
<header>
<param name="SN" value="0" />
<param name="Domain" value="default" />
<param name="User" value="admin" />
<param name="Cmd" value="GetDeviceInfo" />
<param name="Retries" value="0" />
<param name="Timeout" value="5000" />
<param name="Timestamp" value="NA" />
<param name="AuthInfo" value="39ef0f02a9f4d5799481a8d6f2897a0b" />
<param name="ErrorCode" value="SUCCESS" />
<param name="ErrorInfo" value="NA" />
<param name="ProcessTime" value="1" />
</header>
<GetDeviceInfo>
<param name="BeginDeviceId" value="0" />
<param name="MaxGetCount" value="2" />
<param name="No" value="0" />
<param name="DeviceId" value="1" />
<param name="DeviceSn" value="db00-0030-6602-xxxx" />
<param name="DeviceAlias" value="DWG-16A" />
<param name="DeviceType" value="DWG2000F " />
<param name="MaxPortCount" value="16" />
<param name="AdminStatus" value="ENABLED" />
<param name="RunStatus" value="COMM_FAIL" />
</GetDeviceInfo>
<GetDeviceInfo>
<param name="BeginDeviceId" value="0" />
<param name="MaxGetCount" value="2" />
<param name="No" value="1" />
<param name="DeviceId" value="2" />
<param name="DeviceSn" value="db00-0030-1501-xxxx" />
<param name="DeviceAlias" value="DWG-16B" />
<param name="DeviceType" value="DWG2000B " />
<param name="MaxPortCount" value="16" />
<param name="AdminStatus" value="ENABLED" />
<param name="RunStatus" value="ACTIVE" />
</GetDeviceInfo>
</simsrv>
XML;
$xml = new SimpleXMLElement ( $xmlText );
foreach ( $xml->GetDeviceInfo as $device ) {
$deviceSn = $device->xpath("param[@name='DeviceSn']/@value");
$deviceAlias = $device->xpath("param[@name='DeviceAlias']/@value");
echo "DeviceSn=".(string)$deviceSn[0].
" Alias=".(string)$deviceAlias[0].PHP_EOL;
}
使用样本数据,这会产生......
DeviceSn=db00-0030-6602-xxxx Alias=DWG-16A
DeviceSn=db00-0030-1501-xxxx Alias=DWG-16B
您可以使用...
获取所有细节并构建它们的关联数组$xml = new SimpleXMLElement ( $xmlText );
$devices = [];
foreach ( $xml->GetDeviceInfo as $device ) {
$newDevice = [];
foreach ( $device->param as $element ) {
$newDevice[(string)$element['name']] = (string)$element['value'];
}
$devices[] = $newDevice;
}
print_r($devices);