从SimpleXML对象中提取属性

时间:2011-06-13 15:25:55

标签: php simplexml

如何从此xml对象中提取属性

<designs>
    <tags>
    .
    .
    .
    </tags>
    <templates>
        <template id="photographysite" image="http://example.com/en/previews/photographysitePreview434x326.jpg" name="Shutter" thumb="http://example.com/en/previews/photographysitePreview182x137.jpg">
            <tag>all</tag>
            <tag>featured</tag>
            <tag>personal</tag>
            <tag>portfolio</tag>
            <tag>photography</tag>
            <tag>business</tag>
        </template>
    </templates>
</designs>

如果我将每个对象视为$template,则此语法不起作用。

foreach ($xmldoc->templates as $template) {
    $attributes = $template->attributes();
        echo '<img src="' . $attributes['thumb'] . '" />';
}

2 个答案:

答案 0 :(得分:4)

foreach($template->foo[0]->attributes() as $a => $b):

http://php.net/manual/en/simplexmlelement.attributes.php

答案 1 :(得分:1)

您可以使用数组表示法访问各个属性,例如

foreach ($xmldoc->templates->template as $template) {
    echo '<img src="', $template['thumb'], '"/>';
}

请参阅http://www.php.net/manual/en/simplexml.examples-basic.php#example-4587

相关问题