simplexml_load_string和子节点

时间:2012-07-10 17:32:28

标签: php xml simplexml

我试图从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>

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

不需要字符串,但确实是。

答案 2 :(得分:-1)

另一种解决方案是在通过simplexml_load_string并使用简单的字符串替换它之前删除命名空间ns2,我认为这是一种黑客攻击,但它是我如何做的。

$response = str_replace('ns2:', '', $response);
$parse_xml = simplexml_load_string($response);
相关问题