我有一个XML博客Feed,我正在Wordpress上显示。以下是XML节点的简单表示:
<item>
<title>
Some title
</title>
<description>
Some description
</description>
<category>
category 1
</category>
<category>
category 2
</category>
<category>
category 3
</category>
</item>
所以你会注意到上面的类别节点显示3次,但总是有相同的名称。因此,当我使用下面的PHP在循环中显示XML节点时,我只能得到一个类别节点,因为其余的不是唯一的。
有谁知道我怎么能显示所有这些类别节点?
<?php
$rss = new DOMDocument();
$rss->load('http://blog.com/rss.xml');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'category' => $node->getElementsByTagName('category')->item(0)->nodeValue,
);
array_push($feed, $item);
}
?>
<?php
$limit = 3;
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$description = $feed[$x]['desc'];
$category = $feed[$x]['category'];
echo $title;
echo $desc;
echo $category;
}
?>
答案 0 :(得分:1)
为每个项目保存类别而不是一个类别:
<?php
function domNodeList2Array($node_list)
{
$nodes = [];
foreach ($node_list as $node) {
$nodes[] = $node;
}
return $nodes;
}
$rss = new DOMDocument();
$rss->load('rss.xml');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = [
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'categories' => array_map(function ($item) {
return $item->nodeValue;
}, domNodeList2Array($node->getElementsByTagName('category')))];
array_push($feed, $item);
}
$limit = 1;
for ($x = 0; $x < $limit; $x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$description = $feed[$x]['desc'];
$categories = $feed[$x]['categories'];
echo $title;
echo $description;
foreach ($categories as $category) {
echo $category;
}
}
答案 1 :(得分:1)
由于您始终采用第一个元素(使用[0]
),因此总是选择第一个类别。如果您只是添加foreach
,则可以将它们全部添加...
$rss = new DOMDocument ();
$rss->load ( 'rss.xml' );
$feed = array ();
foreach ( $rss->getElementsByTagName ( 'item' ) as $node ) {
$item = array (
'title' => $node->getElementsByTagName ( 'title' )->item ( 0 )->nodeValue,
'desc' => $node->getElementsByTagName ( 'description' )->item ( 0 )->nodeValue,
'category' => array());
foreach ( $node->getElementsByTagName ( 'category' ) as $cat ) {
$item['category'][] = $cat->nodeValue;
}
array_push ( $feed, $item );
}
foreach($feed as $feedItem ) {
$title = str_replace ( ' & ', ' & ', $feedItem ['title'] );
$description = $feedItem ['desc'];
$category = $feedItem ['category'];
echo $title;
echo $description;
foreach ( $category as $cat ) {
echo "Category:".$cat.PHP_EOL;
}
}
答案 2 :(得分:-1)
你可以使用&#34; simplexml_load_file&#34;返回一个数组。
$xml = simplexml_load_file('http://blog.com/rss.xml');
$results = $xml->xpath('//category');
var_dump($results);