我正在尝试解析“不那么正常”的XML Web服务。 Web服务似乎返回一个字符串,其中XML在该字符串中。
XML看起来像这样:
<string>
<NewDataSet>
<Table>
<CATID>0</CATID>
<DEPID>0</DEPID>
</Table>
<Table>
<CATID>1</CATID>
<DEPID>1</DEPID>
</Table>
</NewDataSet>
<string>
这是我现在的代码,我已经尝试了很多变化,但无法获得任何工作。大多数时候它什么都不返回。我已经回显了$ xml,它将返回所有的XML,但我只需要显示CATID而不是其他内容。
<?php
$file = file_get_contents('http://theWebSericeLink.here');
$xml = simplexml_load_string($file);
//echo $xml;
foreach($xml->Table as $item) {
echo $item->CATID;
}
?>
我也试过了:
foreach($xml->NewDataSet->Table as $item)
和
foreach($xml->String->NewDataSet->Table as $item)
提前致谢。
答案 0 :(得分:1)
试试这个
<?php
$k = '<string>
<NewDataSet>
<Table>
<CATID>0</CATID>
<DEPID>0</DEPID>
</Table>
<Table>
<CATID>1</CATID>
<DEPID>0</DEPID>
</Table>
</NewDataSet>
</string>';
$xml = simplexml_load_string($k);
foreach($xml->NewDataSet->Table as $read){
echo $read->CATID."<br>";
}
?>
输出
0
1
答案 1 :(得分:0)
如果您在回显它时可以看到XML,那么您可能需要使用xpath。
$id = $xml->xpath('/table/CATID');
答案 2 :(得分:0)
首先,在结尾处关闭标记,然后以“print_r
”xml变量开头。
print_r($xml);
由于有父母和子女的标签,因此通过每个字段获得结果就像array
。
在你的情况下,
<string>
<NewDataSet>
<Table>
所以
$tables = $xml->NewDataSet->Table;
foreach ($tables as $table)
{
foreach ($table->CATID as $catid){
echo $catid, "\n";
}
}
答案 3 :(得分:0)
我明白了。
在我的foreach函数之前,我从Web服务返回的“xml字符串”创建了一个xml文件:
$xml = simplexml_load_string($file);
$feed = '<?xml version="1.0" encoding="ISO-8859-1"?>'.$xml;
file_put_contents("workhorse.xml", $feed);
$myxml=simplexml_load_file("workhorse.xml");