【问题标题】:find if a child node exists using php使用php查找子节点是否存在
【发布时间】:2012-07-18 20:14:22
【问题描述】:

我已经对此进行了一段时间的研究,但似乎无法找到我的代码的问题。我正在尝试获取商品的价格,如果有价格,这很好用,但如果缺少价格,则会引发错误。
代码如下:

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

【问题讨论】:

    标签: php xml xml-parsing


    【解决方案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;
       }
    }
    

    【讨论】:

    • 我收到此错误 PHP 致命错误:在以 $result = $parsed_xml 开头的行上的非对象上调用成员函数 xpath()
    • 是的,只是注意到如果您更改为 $xml->xpath,$parsed_xml 未在函数中的任何位置定义,应该可以解决您的问题。更新了我的答案
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 2011-04-16
      • 2011-06-09
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多