我有XML
个数据,其中某些商品标签包含 media:content 标签。如何检查XML
中是否存在该内容,以及如何在 media:content 标记下进行说明?
这是XML
数据:
<rss xmlns:content="" xmlns:wfw="" xmlns:dc="" xmlns:atom="" xmlns:sy="" xmlns:slash="" version="2.0">
<channel>
<item>
<title>Title1</title>
<link>Link</link>
<pubDate>Date</pubDate>
<content:encoded>
<![CDATA[ This is description 1 ]]>
<![CDATA[ This is description 2 ]]>
</content:encoded>
<media:content url="URL" type="image/jpeg">
<media:description>
<![CDATA[ Text ]]>
</media:description>
</media:content>
</item>
<item> -- this item tag does not have media: content
<title>Title2</title>
<link>Link2</link>
<pubDate>Date2</pubDate>
<content:encoded>
<![CDATA[ This is description 3 ]]>
<![CDATA[ This is description 4 ]]>
</content:encoded>
</item>
<item>
<title>Title3</title>
<link>Link3</link>
<pubDate>Date3</pubDate>
<content:encoded>
<![CDATA[ This is description 5 ]]>
<![CDATA[ This is description 6 ]]>
</content:encoded>
<media:content url="UR1L" type="image/jpeg">
<media:description>
<![CDATA[ Text 2 ]]>
</media:description>
</media:content>
</item>
</channel>
</rss>
我尝试的是:
<?php
function feeds()
{
$url = "http://localhost/xmldata/xmld.xml"; // xmld.xml contains above data
$feeds = file_get_contents($url);
$rss = simplexml_load_string($feeds);
foreach($rss->channel->item as $entry) {
if($entry->children('media', true)->content->attributes()) {
$md = $entry->children('media', true)->content->attributes();
print_r("$md->url");
}
}
}
?>
它返回我的错误如下:
节点不再存在
即使我不知道媒体:内容标记中的媒体:描述。
答案 0 :(得分:2)
您可以使用isset来检查“媒体:内容”是否正确。属性设置在SimpleXMLElement。
我认为如果你改变这些行会有所帮助:
foreach($rss->channel->item as $entry) {
if($entry->children('media', true)->content->attributes()) {
$md = $entry->children('media', true)->content->attributes();
print_r("$md->url");
}
}
到这些方面:
$rss = @simplexml_load_string($feeds);
foreach ($rss->channel->item as $entry) {
if (isset($entry->{'media:content'})) {
$url = (string)$entry->{'media:content'}->attributes()->url;
$description = (string)$entry->{'media:content'}->{'media:description'};
echo "$url<br>";
echo "$description<br>";
}
}
将导致:
URL
文本
UR1L
文字2
答案 1 :(得分:1)
这对我有用。
$namespaces = $entry->getNamespaces(true);
$media_url = trim((string)$entry->children($namespaces['media'])->content->attributes()->url);