simplexml_load_string和子节点


simplexml_load_string and child nodes

我正在尝试从xml字符串中获取信息并查看其中的子节点

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

在数组中$current

$current = $parsed_xml->ListMatchingProductsResponse->ListMatchingProductsResult->Products->Product;

命名空间是ns2,子项是ItemAttributes和Title。当我运行这个时,我没有得到标题应该在哪里的信息

SimpleXMLElement Object()

有人能给我指正确的方向吗?我看过其他帖子,并尝试使用它们的例子,但它们对我不起作用。这是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>

通常需要将simpleXml元素强制转换为字符串才能获得值。尝试'Title' => (string)$current->AttributeSets->children('ns2')->ItemAttributes->Title

如果其他人需要做类似的事情,获取子级信息的正确方法是:

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

字符串不是必需的,但true是。

另一个解决方案是在通过simplexml_load_string之前删除名称空间ns2,并用一个简单的字符串替换,我认为这有点像黑客,但这就是我的做法。

$response = str_replace('ns2:', '', $response);
$parse_xml = simplexml_load_string($response);