我一直在尝试使用foreach循环提取节点数据的子节点。我可以毫无问题地获得主节点数据,但子数据只获得第一个数据集然后重复。有人可以告诉我我做错了什么吗?我从官方文档中得到了示例:http://php.net/manual/en/simplexmlelement.children.php
这是我的测试xml
<Result>
<Result_Data>
<Root_XML>
<Stock>
<Stock_Code>28</Stock_Code>
<Barcode>28</Barcode>
<Multiple_Barcodes>
<Barcode>BARCODE1</Barcode>
<Barcode>BARCODE2</Barcode>
</Multiple_Barcodes>
<Sell_Prices>
<Sell_Price>
<Inclusive>10</Inclusive>
<Exclusive>8.77193</Exclusive>
</Sell_Price>
<Sell_Price>
<Inclusive>0</Inclusive>
<Exclusive>0</Exclusive>
</Sell_Price>
<Sell_Price>
<Inclusive>0</Inclusive>
<Exclusive>0</Exclusive>
</Sell_Price>
</Sell_Prices>
<New_Prices>
<New_Price>0</New_Price>
<New_Price>0</New_Price>
<New_Price>0</New_Price>
<New_Price>0</New_Price>
</New_Prices>
<Work_In_Progress_Quantity>0</Work_In_Progress_Quantity>
<Extended_Description />
<Onhand>0</Onhand>
</Stock>
<Stock>
<Stock_Code>123</Stock_Code>
<Barcode>123</Barcode>
<Multiple_Barcodes>
<Barcode>BARCODE123</Barcode>
<Barcode>BARCODE124</Barcode>
</Multiple_Barcodes>
<Sell_Prices>
<Sell_Price>
<Inclusive>10</Inclusive>
<Exclusive>8.77193</Exclusive>
</Sell_Price>
<Sell_Price>
<Inclusive>0</Inclusive>
<Exclusive>0</Exclusive>
</Sell_Price>
<Sell_Price>
<Inclusive>0</Inclusive>
<Exclusive>0</Exclusive>
</Sell_Price>
</Sell_Prices>
<New_Prices>
<New_Price>0</New_Price>
<New_Price>0</New_Price>
<New_Price>0</New_Price>
<New_Price>0</New_Price>
</New_Prices>
<Work_In_Progress_Quantity>0</Work_In_Progress_Quantity>
<Extended_Description />
<Onhand>0</Onhand>
</Stock>
</Root_XML>
</Result_Data>
这是我的php代码
$file = file_get_contents('play.xml', true);
$XMLtoSAVE = new SimpleXMLElement($file);
foreach ($XMLtoSAVE->Result_Data->Root_XML->Stock as $element) {
echo $element->Stock_Code . "\n";
//Child Node Data - Barcode
foreach ($XMLtoSAVE->Result_Data->Root_XML->Stock->Multiple_Barcodes as $element) {
echo $element->Barcode . "\n";
}
}
这是输出:
28
条形码1
123
条形码1
预期输出:
28
条形码1
条形码2
123
BARCODE123
BARCODE124
答案 0 :(得分:1)
在内循环中使用foreach ($element->Multiple_Barcodes->Barcode as $barcode) { echo $barcode; }
。