我一直试图解析这些数据一段时间,但我并不真正理解simpleXML以及它如何存储/检索。我有以下xml:
<ListOrderItemsResult>
<OrderItems>
<OrderItem>
<QuantityOrdered>1</QuantityOrdered>
<Title>Organic Chamomile & Lavender Shea Butter CP Soap Making Kit 2 Lbs.</Title>
<ItemPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>29.99</Amount>
</ItemPrice>
<ItemTax>
<CurrencyCode>USD</CurrencyCode>
<Amount>0.00</Amount>
</ItemTax>
</OrderItem>
<OrderItem>
<QuantityOrdered>1</QuantityOrdered>
<Title>Eucalyptus & Mint Organic Shea Butter CP Soap Making Kit 3 lbs.</Title>
<ItemPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>32.99</Amount>
</ItemPrice>
<ItemTax>
<CurrencyCode>USD</CurrencyCode>
<Amount>0.00</Amount>
</ItemTax>
</ShippingDiscount>
</OrderItem>
</OrderItems>
<AmazonOrderId>12134</AmazonOrderId>
</ListOrderItemsResult>
我正在尝试将其转换为csv,每个OrderItem都是一行。列是:QuantityOrdered,Title,ItemPrice,ItemTax。到目前为止,我已经设法抓住了除ItemPrice和ItemTax之外的所有内容,因为它们有子节点,我不知道如何访问它们。
这是我的代码:
$OrderItem = $xmlDocs->xpath('//a:OrderItem');
foreach($ OrderItem为$ n){
foreach ($AmazonOrderId as $t) {
$row[]=$t;
}
// Iterate through each child of <OrderItem> node
$child = $xml->xpath('//a:OrderItem['.$i.']/*');
foreach ($child as $value) {
$row[] = $value;
}
print_r($row);
$fs = fopen('141.csv', 'a');
fputcsv($fs, $row);
$row = [];
// Clean out array for next <item> (i.e., row)
$i++; // Move to next <item> (i.e., node position)
}
FCLOSE($ FS);
我有它的工作,但是因为我无法弄清楚如何找到孩子的孩子,所以没有任何东西出现在ItemPrice和ItemTax上。
TL; DR - 我正在尝试遍历每个OrderItem节点并获取每个子节点的值,如果子节点有子节点,我只想获取名为“Amount”的节点的值。
答案 0 :(得分:0)
我想出了怎么做。我必须真正分解simplexml才能理解对象层是如何分层的,以便我能够弄清楚如何提取我想要的数据。希望这对某人有意义,但是当您尝试从SimpleXML对象中提取特定值时,您希望它在print_r()时读取:
SimpleXMLElement Object
(
[0] => 0 //0 being the value you want - you can now add this to whatever variable you want once you have it down to this.
)
以下是执行此操作的代码:
//Iterate through the first node <OrderItem>
foreach ($OrderItem as $n) {
//Add the AmazonOrderId to the start of each line
foreach ($AmazonOrderId as $t) {
$row[]=$t;
}
$child = $xml->xpath('//a:OrderItem['.$i.']/*');
// Iterate through each child of <OrderItem> node
foreach ($child as $value) {
//If the child has an attribute named <Amount>
if($value->Amount[0]){
//Iterate through and grab the value of <Amount> and post add to $row
foreach ($value->Amount as $t) {
$row[] = $t;
}
}
//Else add the value to $row
else {
$row[] = $value;
}
}
$fs = fopen('141.csv', 'a');
fputcsv($fs, $row);
$row = [];
$i++;
}
fclose($fs);