Jim
Jim

Reputation: 1315

find if a child node exists using php

I have been researching this for a while and can't seem to find the problem with my code. I am attempting to get the price of an item and this works great if there is a price, but if the price is missing it throws an error.
Here is the code:

    /* 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); 

My function to check for child nodes is:

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

Upvotes: 1

Views: 1759

Answers (2)

lusketeer
lusketeer

Reputation: 1930

Use property_exists() I'm using it to check duplicated child while adding new child into xml using SimpleXML. It should work for you. If you just pass in the child name, and its parent.

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

Upvotes: 1

Gntem
Gntem

Reputation: 7155

try this to check if child node exists

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

Upvotes: 1

Related Questions