2012-07-18 28 views
1

我一直在研究這一段時間,似乎無法找到與我的代碼的問題。我試圖得到一個項目的價格,如果有價格,這個工程很好,但如果價格不足,就會拋出一個錯誤。
下面是代碼:找到一個孩子節點是否存在使用php

/* Amazon Offers ALGORITHM */ 
$parsed_xml = amazon_xml($isbn); 

$current = $parsed_xml->ListMatchingProductsResult->Products->Product; 
$asin = $current->Identifiers->MarketplaceASIN->ASIN; 

// get information based on the items ASIN 
$price_xml = amazonPrice_xml($asin); 
    if($price_xml) { 
    while(count($lowestPrices) < 2) 
    { 

     // check to see if there are values 
     if(xml_child_exists($parsed_xml, $current->AttributeSets->children('ns2', true)->ItemAttributes->ListPrice->Amount)) 
      { 
      $listPrice = $current->AttributeSets->children('ns2', true)->ItemAttributes->ListPrice->Amount; 
      } else { 
      $listPrice = 0; 
      } 
     $currentPrice = $price_xml ->GetLowestOfferListingsForASINResult->Product->LowestOfferListings->LowestOfferListing; 
     print_r($listPrice); 

我的函數來檢查子節點是:

function xml_child_exists($xml, $childpath) 
{ 
$result = $parsed_xml->xpath($childpath); 
if (count($result)) { 
    return true; 
} else { 
    return false; 
} 
} 

回答

1

試試這個檢查,如果子節點存在

function xml_child_exists($xml, $childpath) 
{ 
    //$result = $parsed_xml->xpath($childpath); $parsed_xml variable? 
    $result = $xml->xpath($childpath); 
    if (isset($result)) { // changed from count to isset 
    return TRUE; 
    } else { 
    return FALSE; 
    } 
} 
+0

我得到這個錯誤PHP致命錯誤:調用一個成員函數的XPath()就行了非對象以$結果開始= $ parsed_xml – Jim 2012-07-18 20:19:36

+0

耶剛注意到$ parsed_xml沒有在函數的任何地方定義,如果你改爲$ xml-> xpath,應該可以解決你的問題。更新了我的答案 – Gntem 2012-07-18 20:23:41

+0

感謝您的幫助。這讓它工作。 – Jim 2012-07-19 12:20:35

1

使用property_exists() 我用它來檢查重複的孩子,而使用SimpleXML添加新的子轉換成XML 。它應該適合你。如果您只是傳入子名稱及其父項。

function xml_child_exists($xml, $child) 
{ 
return property_exists($xml, $child); 
} 
相關問題