在非对象上调用成员函数children()

时间:2012-07-11 19:17:49

标签: php xml parsing simplexml

当我尝试从XML文件中提取信息时,我收到此错误。获取信息的代码是:

//retrieve amazon data
$parsed_xml = amazon_xml($isbn);
$amazonResult = array();

    //print_r($parsed_xml); die;
$current = $parsed_xml->ListMatchingProductsResponse->ListMatchingProductsResult->Products->Product;
    //if($parsed_xml) {

        $amazonResult = array(
            'Title' => $current->AttributeSets->children('ns2')->ItemAttributes->Title,
            'SalesRank' => $current->SalesRankings->SalesRank->Rank,
            'ListPrice' => $current->AttributeSets->ItemAttributes->ListPrice->Amount,
            'ImageURL' => $current->AttributeSets->ItemAttributes->SmallImage->URL,
            'DetailURL' => $current->AttributeSets->ItemAttributes->SmallImage->URL,

,XML文件是:

<?xml version="1.0"?>
<ListMatchingProductsResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<ListMatchingProductsResult>
<Products xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
<Product>
<AttributeSets>
<ns2:ItemAttributes xml:lang="en-US">
<ns2:Title>JavaScript: The Missing Manual</ns2:Title>

当我运行这个时,我得到一个空值,当我检查错误日志时,我得到: 在第52行的...中的非对象上调用成员函数children()。 违规行是:

'Title' => $current->AttributeSets->children('ns2')->ItemAttributes->Title,

唯一具有ns2名称空间的项是ItemAttributes和Title。

如何更正此问题以便获取标题信息? 感谢

1 个答案:

答案 0 :(得分:1)

ns2是前缀,而不是实际的命名空间,ListMatchingProductsResponse是根节点,不需要提及它,所以:

var_dump(
        $parsed_xml->ListMatchingProductsResult
                ->Products
                ->Product
                ->AttributeSets
                ->children('ns2',true)
                ->ItemAttributes
                ->Title);