我有以下php代码:
$xml=simplexml_load_file("http://openclipart.org/api/search/?query=dog&page=1");
echo "<ul>";
foreach ($xml->channel->item as $clipinfo):
$title=$clipinfo->title;
$full=$clipinfo->enclosure['url'];
$thumb=$clipartinfo->children('media', true)->thumbnail['url'];
echo "<div style='"width:160px;height:120px;float:left;margin:5px;margin-top:10px;'">
<a href='"{$full}'" target='_blank' class='"thumbnail'">
<img alt='"{$title}'" style='"width: 160px; height: 120px;'" src='"{$thumb}'">
</a>
</div>";
endforeach;
这是由以下 XML 文件提供的:
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:cc="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:media="http://search.yahoo.com/mrss/" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>OpenClipart.org</title>
<atom:link rel="self" href="http://openclipart.org/api/search/?query=dog&page=1" type="application/rss+xml"/>
<link>http://openclipart.org</link>
<description>Download, Sample, Cut-up, Share.</description>
<language>en-US</language>
<image>
<url>http://openclipart.org/assets/images/images/logo-no-text.jpg</url>
<link>http://openclipart.org</link>
<title>OpenClipart.org</title>
<height>93</height>
<width>114</width>
</image>
<item>
<title>walking dog</title>
<link>http://openclipart.org/detail/720/walking-dog-by-johnny_automatic</link>
<pubDate>Tue, 17 Oct 2006 21:23:37 -0400</pubDate>
<dc:creator>johnny_automatic</dc:creator>
<description>cartoon of a girl walking a dog from http://www.usda.gov/cnpp/KidsPyra/National Agricultural Library, Agricultural Research Service, U. S. Department of Agriculture</description>
<enclosure url="http://openclipart.org/people/johnny_automatic/johnny_automatic_walking_dog.svg" type="image/svg+xml" length="99841"/>
<guid>http://openclipart.org/detail/720/walking-dog-by-johnny_automatic</guid>
<cc:license>http://creativecommons.org/licenses/publicdomain</cc:license>
<media:thumbnail url="http://openclipart.org/image/90px/svg_to_png/720/johnny_automatic_walking_dog.png"/>
</item>
为什么我不能通过我的 foreach 语句获取 <media:thumbnail>
url 属性?(我已经阅读了用于解析标签名称中带有冒号的XML的PHP库?这是一个不同的问题。
首先,你在foreach
循环中使用了一个未定义的变量。你已经定义了$clipinfo
但你正在尝试在代码中使用$clipartinfo
。
其次,您错误地访问了属性:
<media:thumbnail url="http://openclipart.org/image/foo.png"/>
您正在尝试访问网址属性。这需要通过attributes()
方法完成。
改变:
$thumb=$clipartinfo->children('media', true)->thumbnail['url'];
自:
$thumb = $clipinfo->children('media', true)->thumbnail->attributes()->url;
希望这有帮助!
属性不会自动与它们所在的元素位于同一命名空间中。如果 XML 包含 <media:thumbnail media:url="...." />
,则该属性将位于当前分配了前缀 media
的命名空间中,与 thumbnail
元素的命名空间相同,并且您的代码可以正常工作。
但是,XML 命名空间规范的一个怪癖是"无前缀属性名称的命名空间名称始终没有值",也就是说,没有命名空间前缀的属性显式不在任何命名空间中,而不考虑文档中定义了其他内容。(另请参阅 XML 命名空间和无前缀属性)
在 SimpleXML 中,这意味着如果您已切换到具有 ->children
的特定命名空间,则必须使用 ->attributes()
方法显式切换回"null"命名空间才能访问该属性。这应该有效:
$thumb = $clipinfo->children('media', true)->thumbnail->attributes(null)->url;