如何通过调用它们的“columnId”而不是数组中的位置来用php回显xml值? (阵列真的很长)
以下是xml的示例:
<Data>
<Value columnId="ITEMS_SOLD">68</Value>
<Value columnId="TOTAL_SALES">682</Value>
<Value columnId="SHIPPING_READY">29</Value>
...
</Data>
以下php为我提供了所有值:
$url = 'XXX';
$xml = file_get_contents($url);
$feed = simplexml_load_string($xml) or die("Error: Cannot create object");
foreach($feed->Data->Value as $key => $value){
echo $value;
}
我希望能够在我的文档中使用类似的内容:
echo $feed->Data->Value['TOTAL_SALES'];
感谢您的帮助。
答案 0 :(得分:0)
echo $feed->Data->Value[1];
答案 1 :(得分:0)
我还有另一种解决方案。您可以将 xml对象转换为数组,并将其用于进一步处理。试试这段代码:
<?php
$url = 'XXX';
//Read xml data, If file exist...
if (file_exists($url)) {
//Load xml file...
$xml = simplexml_load_file($url);
$arrColumn = array();//Variable initialization...
$arrFromObj = (array) $xml;//Convert object to array...
$i = 0;//Variable initialization with value...
//Loop until data...
foreach($xml AS $arrKey => $arrData) {
$columnId = (string) $arrData['columnId'][0];//array object to string...
$arrColumn[$columnId] = $arrFromObj['Value'][$i];//assign data to array...
$i++;//Incremental variable...
}
} else {//Condition if file not exist and display message...
exit('Failed to open file');
}
?>
上面的代码会将结果存储到数组变量$arrColumn
中,结果为:
Array
(
[ITEMS_SOLD] => 68
[TOTAL_SALES] => 682
[SHIPPING_READY] => 29
)
希望这对你有所帮助!
答案 2 :(得分:0)
使用XPath。 SimpleXML和DOM支持它,但SimpleXML有一些限制(它只能获取节点列表)。
$feed = simplexml_load_string($xml);
var_dump(
(string)$feed->xpath('//Value[@columnId = "TOTAL_SALES"]')[0]
);
输出:
string(3) "682"
$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);
var_dump(
$xpath->evaluate('string(//Value[@columnId = "TOTAL_SALES"])')
);
输出:
string(3) "682"