使用php simpleXML获取值

时间:2012-07-25 10:41:45

标签: php xml simplexml

我正在尝试遍历底部xml中的images节点,但我的代码只显示了许多中的第一个图像。我正在使用foreach遍历它,任何帮助都将非常感激。

另外,我正在尝试访问产品下的“描述”和“功能”,但我无法弄清楚如何访问这些内容。

    <?php 
    $mypix = simplexml_load_file('abc.xml');
    foreach ($mypix->package as $pixinfo):
        $title=$pixinfo->productTitle;
        $link=$pixinfo->url;
        $image=$pixinfo->imageUrl;    
        echo "<a href=\"",$link,"\"><img src=\"",$image,"\" alt=\"",$title,"\" height=\"100\" width=\"100\" /></a>\n";
        foreach ($pixinfo->images as $piximages):
            echo "<img src=\"",$piximages->image,"\" height=\"50\" width=\"50\" />\n";
        endforeach;
        echo "<br />";
    endforeach;
?>


    <?xml version="1.0" encoding="utf-8" ?>
<packages xmlns="http://www.google.com">
    <package>
        <productTitle>Product A</productTitle>
        <url>http://google.com</url>
        <imageUrl>h658279.jpg</imageUrl>
        <images>
            <image>658279.jpg</image>
            <image>658280.jpg</image>
            <image>658283.jpg</image>
        </images>
        <products>
            <product>
                <description>Why choose product</description>
                <locationDescription>Ideally located</locationDescription>
                <features>Buttons 12</features>
            </product>
        </products>
    </package>
</packages>

2 个答案:

答案 0 :(得分:1)

尝试一次(测试)......

<?php
$mypix = simplexml_load_file('abc.xml');
foreach ($mypix->package as $pixinfo):
    $title = $pixinfo->productTitle;
    $link = $pixinfo->url;
    $image = $pixinfo->imageUrl;
    echo "<a href=\"", $link, "\"><img src=\"", $image, "\" alt=\"", $title, "\" height=\"100\" width=\"100\" /></a>\n";
    foreach ($pixinfo->images->image as $img) {
        echo "<img src=\"". $img. "\" height=\"50\" width=\"50\" />\n";
    }
    echo "<br />";
endforeach;
?>

答案 1 :(得分:0)

你有一个错字,它应该是:

 foreach ($mypix->packages as $pixinfo): //packages not package