我需要从XML字符串中解析一些字段。我的PHP代码如下:
$oscam2 = simplexml_load_string($xml2);
//$oscam2 = simplexml_load_string($xml2, 'SimpleXMLElement', LIBXML_NOEMPTYTAG);
$oscaa = $oscam2->status->client[2][request]['caid'];
echo $oscaa;
die(var_dump($oscaa));
我的XML文件如下:
<oscam version="1.20-unstable_svn build r10649"revision="10649" starttime="2015-05-27T06:41:07-0400"uptime="954150" readonly="0">
<status>
<client type="s" name="root" desc="" protocol="server"protocolext="" au="0" thid="id_0x1d3d260">
<request caid="0000" srvid="0000" ecmtime=""ecmhistory="" answered=""/>
<times login="2015-05-27T06:41:07-0400" online="954150"idle="740499"/>
<connection ip="127.0.0.1" port="0">OK</connection>
</client>
<client type="h" name="root" desc="" protocol="http"protocolext="" au="0" thid="id_0x7f8e8c0008c0">
<request caid="0000" srvid="0000" ecmtime=""ecmhistory="" answered=""/>
<times login="2015-05-27T06:41:07-0400" online="954150"idle="0"/>
<connection ip="127.0.0.1" port="0">OK</connection>
</client>
<client type="p" name="Sky" desc="" protocol="cccam_ext (2.2.1-3316)" protocolext="OSCam v1.20-unstable_svn, build r10666 (x86_64-linux-gnu-ssl) [EXT,SID,SLP]"au="-1" thid="id_0x7f8e74006340">
<request caid="0000" srvid="0000" ecmtime=""ecmhistory="" answered=""/>
<times login="2015-06-05T15:53:12-0400" online="143425"idle="143383"/>
<connection ip="XXX"port="34010">OFF</connection>
</client>
</status>
<log>
<![CDATA[
logdata
]]>
<![CDATA[
logdata
]]>
</log>
</oscam>
如您所见,我想解析元素“Sky”的[request] ['caid']字段的内容(“0000”)。知道怎么做到这一点?请求和时间的XML是自我封闭的。
答案 0 :(得分:0)
我相信您需要执行以下操作才能获得元素属性。
$oscam2->status->client[2]->request->attributes()['caid'];
如果这对您不起作用,那么您使用的是较旧的PHP版本,需要执行类似的操作
$attributes = $oscam2->status->client[2]->request->attributes();
$value = $attributes['caid'];
答案 1 :(得分:0)
首先,检查simpleXML是否可以读取您的字符串,因为属性之间没有空格。如果解析xml时没有错误,则可以使用xpath不依赖于client
项的更改顺序。它需要client
个节点name
等于'Sky'
,然后在caid
节点的属性request
内:
$oscam2 = simplexml_load_string($xml2);
if(!$oscam2) die("Error reading xml string");
$caid = (string)$oscam2->xpath('//client[@name="Sky"]/request/@caid')[0];
echo $caid; // 0000