使用php查找是否存在子节点

使用php查找是否存在子节点,php,xml,xml-parsing,Php,Xml,Xml Parsing,我已经对此进行了一段时间的研究,但似乎找不到我的代码的问题。我正在尝试获取物品的价格,如果有价格,这非常有效,但如果价格丢失,则会抛出错误。 代码如下: /* Amazon Offers ALGORITHM */ $parsed_xml = amazon_xml($isbn); $current = $parsed_xml->ListMatchingProductsResult->Products->Product; $asin = $current->Iden

我已经对此进行了一段时间的研究,但似乎找不到我的代码的问题。我正在尝试获取物品的价格,如果有价格,这非常有效,但如果价格丢失,则会抛出错误。
代码如下:

    /* 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); 
使用 我使用它来检查重复的子对象,同时使用SimpleXML将新的子对象添加到xml中。它应该对你有用。如果您只是传入子名称及其父名称

function xml_child_exists($xml, $child)
{
 return property_exists($xml, $child);
}

尝试此操作以检查子节点是否存在

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;
   }
}

我得到了这个错误PHP致命错误:在以$result=$parsed_xmlyea开头的行上的非对象上调用成员函数xpath()。我刚刚注意到,如果更改为$xml->xpath,函数中的任何地方都没有定义$parsed_xml,应该可以解决问题。更新了我的答案
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;
   }
}