我使用以下代码在PHP中提取RSS提要。
$var = (array) simplexml_load_file($rssfeed);
一切都很好。 我能够循环浏览 RSS 提要,并在我想做的$var内对 RSS 提要进行所有处理。 问题是我希望能够将两个 RSS 提要合并在一起。
所以我使用相同的代码从simplexml_load_file获取值并使用$items = $var->item;
提取项目,但我无法弄清楚如何在两个 RSS 提要之间合并项目子数组中的两个值。 我尝试使用array_merge,array_combine并用加号将它们串在一起。 我最终得到来自第一个 RSS 提要或第二个的值,但不是一组合并的值。
有没有人有任何想法(慢慢说,我是DBA职业)。
TIA,丹尼
尝试这样的事情,使用递归函数将整个xml对象转换为数组,数组合并是不够的,合并后您可以将其转换回和对象。我认为问题是如果正在提交的两个 xml 文件具有相同的元素,它们可能会被合并覆盖。
function recursive_object_to_array($obj) {
if(is_object($obj)) $obj = (array) $obj;
if(is_array($obj)) {
$new = array();
foreach($obj as $key => $val) {
$new[$key] = recursive_object_to_array($val);
}
}
else $new = $obj;
return $new;
}
if (file_exists('test_folder/rss1.xml') && file_exists('test_folder/rss2.xml')) {
$rss1 = recursive_object_to_array(simplexml_load_file('test_folder/rss1.xml'));
$rss2 = recursive_object_to_array(simplexml_load_file('test_folder/rss2.xml'));
$rss_combined = (object) array_merge((array) $rss1, (array) $rss2);
var_dump($rss1); //content of first rss file
var_dump($rss2); //content of second rss file
var_dump($rss_combined); // contents when recombined as object
//this is my best bet, since the array keys are the same for the example i used, you need to create an associative array and loop over it.
$all_rss[1] = $rss1;
$all_rss[2] = $rss2;
var_dump($all_rss); // creates asscociative array on which to loop
} else {
exit('Failed to open xml files.');
}
所以最后我会使用数组来访问元素。我在下面的链接RSS W3schools中使用了xml文件
// get the xml
$rss1 = recursive_object_to_array(simplexml_load_file('test_folder/rss1.xml'));
$rss2 = recursive_object_to_array(simplexml_load_file('test_folder/rss2.xml'));
// create assoaciative array
$all_rss[1] = $rss1;
$all_rss[2] = $rss2;
// loop over array
foreach($all_rss as $key=>$value){
echo $value['channel']['title'];
echo '</br></br>';
echo $value['channel']['link'];
echo '</br></br>';
}