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


find if a child node exists using 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;
}
}

尝试检查子节点是否存在

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

使用property_exists()我使用它来检查重复的子项,同时使用SimpleXML将新的子项添加到xml中。它应该对你有用。如果您只传入子名称及其父名称。

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