访问子元素

时间:2018-03-29 02:14:41

标签: php xml

我有这个xml代码,我需要从中获取每个值。我已经尝试了,但我得到的只是第一个值。我想知道我的代码有什么问题。

这里是xml代码:

<item>
    <g:detailed_images>
        <g:detailed_image>hat.png</g:detailed_image>
        <g:detailed_image>tie.png</g:detailed_image>
        <g:detailed_image>eye_glass.png</g:detailed_image>
        <g:detailed_image>watch.png</g:detailed_image>
    </g:detailed_images>
</item>
<item>
    <g:detailed_images>
        <g:detailed_image>shoe.png</g:detailed_image>
        <g:detailed_image>socks.png</g:detailed_image>
        <g:detailed_image>hand_gloves.png</g:detailed_image>
        <g:detailed_image>scarf.png</g:detailed_image>
    </g:detailed_images>
</item>

这是我的代码:

foreach($xpath->evaluate('//item') as $item)
    {
        $detailed_images = $xpath->evaluate('g:detailed_images', $item);

        foreach ($detailed_images as $img)
        {
            $simg = $xpath->evaluate('string(g:detailed_image)', $img);
            echo 'image = ';
            echo $simg;
        }
    }

我的结果是:

image = hat.png
image = shoe.png

虽然我想要的是这个:

image = hat.png
image = tie.png
image = eye_glass.png
image = watch.png
image = shoe.png
image = socks.png
image = hand_gloves.png
image = scarf.png

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

如您所见,您只获得了每个detailed_image的第一个detailed_images。因此,保持您的工作方式,您需要在foreach上设置另一个$simg并打印每个结果节点。但是,您不需要执行所有XPath查询来获取这些元素。只需一个查询就可以到达那里:

//item/g:detailed_images/g:detailed_image

PHP代码:

$dom = new DOMDocument;
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
foreach($xpath->evaluate('//item/g:detailed_images/g:detailed_image') as $item) {
        var_dump($item->nodeValue);
}

Demo