I'm trying to sort the item elements of an RSS feed. I'm almost there and just neeed to get the sorted items back into the simpleXML of the feed. I've read the feed using:
$xml = file_get_contents($myUrl);
$data = simplexml_load_string($xml);
To be able to use usort
I've pulled the items into an array:
$sortable = array();
foreach($data->channel->item as $node) {
$sortable[] = $node;
}
more code to do the actual sorting, of the form:
function sorttitlelowhigh($a,$b) {
return strcmp($a->title, $b->title);
};
and called with:
usort($sortable, 'sorttitlelowhigh');
I've removed the original items from $data using:
$elementsToRemove = array();
$i = 0;
foreach($data->channel->item as $item) {
if ($i >= 0) {
$elementsToRemove[] = $item;
}
$i++;
}
foreach ($elementsToRemove as $item) {
unset($item[0]);
}
and it's the last step I can't seem to get right, getting the sorted items back into $data. Note that some elements of the feed contains namespaces and CDATA.
I've tried:
foreach($sortable as $item){
$data->channel->addChild("item", $item);
}
and many other variations. I know that $item contains what I need because displaying it with:
$xml2=$item->asXML();
$xml2 = str_replace('&', '&', $xml2);
$xml2 = str_replace('<', '<', $xml2);
echo '<pre>' . $xml2 . '</pre>';
shows its content. I've shortened things by putting a description inbetween braces {} and prettied up the output here by hand:
<item>
<guid isPermaLink="false">https://www.zazzle.com/pink_and_satin_fabric_effect_with_your_initials_compact_mirror-256359221382338484</guid>
<pubDate>Sat, 24 Jun 2017 18:53:36 GMT</pubDate>
<title><![CDATA[ {text} ]]></title>
<link>https://www.zazzle.com/pink_and_satin_fabric_effect_with_your_initials_compact_mirror-256359221382338484</link>
<author>HightonRidley</author>
<description><![CDATA[ {text} ]]></description>
<price>$19.50</price>
<media:title><![CDATA[ {text} ]]></media:title>
<media:description><![CDATA[ {text} ]]></media:description>
<media:price>$19.50</media:price>
<media:thumbnail url=" {a url} "/>
<media:content url=" {a url} "/>
<media:keywords><![CDATA[ {text} ]]></media:keywords>
<media:rating scheme="urn:mpaa">g</media:rating>
</item>
...but no matter what I try, I can't get the items back into $data. The closest I got was empty items when I used:
foreach($sortable as $item){
$data->channel->addChild("item", $item->asXML());
}
Can anyone help me with this last step?