我正試圖對我從一個API呼叫中得到的XML輸出進行回圈處理。 該XML的結構如下:
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink"> /span>
<products>/span>
<products>>
<id>/span>97</id>/span>
<id_manufacturer>0</id_manufacturer>/span>
<id_supplier>0</id_supplier>/span>
<width>/span>0.000000</width>/span>
<height>/span>0.000000</height>
<depth>0.000000</depth>
<weight>1.127272</weight>
<quantity_discount> 0</quantity_discount>
<on_sale>0</on_sale>/span>
<online_only>0</online_only>/span>
<minimal_quantity>1</minimal_quantity>
<價格>37.000000</價格>
</product>/span>
<product>...</product>...
<product>...</product>...
<product>...</product>...
<product>...</product>...
</products>/span>
</prestashop>/span>
我想回圈瀏覽所有的產品并獲得例如價格的資訊。 我已經嘗試了不同的方法,比如:
$opt = array(
'資源' => '產品'。
'display' => 'full',
'filter[id]' => $_GET['id'] 。
'postXml' => 'asXML'
);
$xml = $webService->get($opt); //獲取xml資料,如上所示。
foreach ($xml->products-> product as $p) {
echo $p->屬性()->價格。
}
但是,結果是不會顯示任何東西...... 如果你能幫助我,也許有一個解決方案,我將非常高興。
uj5u.com熱心網友回復:
price不是<product>的屬性,它是一個子節點。因此,如果,例如你想提取價格(也就是price元素的字串值),你可以做這樣的事:
$dom = new DOMDocument();
$dom->loadXML($xml)。
$xpath = new DOMXPath($dom)。
$products = $xpath->query("//product") 。
foreach ($products as $prod)
{
foreach ($xpath->query(' .//price',$prod) as $price) {
echo($price->textContent)."
"。
}
};
uj5u.com熱心網友回復:
之前的答案是正確的,但實際上并沒有顯示如何在XML物件上進行回圈。
<?php
$myXMLData = '<prestashop>
<products>/span>
<products>>
<id>/span>97</id>/span>
<id_manufacturer>0</id_manufacturer>/span>
<id_supplier>0</id_supplier>/span>
<width>/span>0.000000</width>/span>
<height>/span>0.000000</height>
<depth>0.000000</depth>
<weight>1.127272</weight>
<quantity_discount> 0</quantity_discount>
<on_sale>0</on_sale>/span>
<online_only>0</online_only>/span>
<minimal_quantity>1</minimal_quantity>
<價格>37.000000</價格>
</product>/span>
<產品>/span>
<id>98</id>/span>
<id_manufacturer>0</id_manufacturer>/span>
<id_supplier>0</id_supplier>/span>
<width>/span>0.000000</width>/span>
<height>/span>0.000000</height>
<depth>0.000000</depth>
<weight>1.127272</weight>
<quantity_discount> 0</quantity_discount>
<on_sale>0</on_sale>/span>
<online_only>0</online_only>/span>
<minimal_quantity>1</minimal_quantity>
<價格>37.000000</價格>
</product>/span>
</products>/span>
</prestashop>' 。
$xml = simplexml_load_string($myXMLData) or die("Error: Cannot create object");
foreach ($xml->products->product as $product){
print_r($product->id)。
/*你可以在這里訪問你所有的產品物件屬性*/。
}
?>。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/324040.html
標籤:
