I am trying to filter the results of an XML feed generated for Facebook. Currently, the feed looks like this
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
<title><![CDATA[Title]]></title>
<link><![CDATA[https:/path/]]></link>
<description>WooCommerce Product List RSS feed</description>
<metadata>
<ref_application_id>451257172939091</ref_application_id>
</metadata>
<item>
<g:id>anID</g:id>
<g:inventory>5</g:inventory>
<g:description><![CDATA[Some Text]]></g:description>
<g:condition>new</g:condition>
<g:mpn>sku</g:mpn>
<g:title>Product Title</g:title>
<g:availability>in stock</g:availability>
<g:price>185.00 EUR</g:price>
<g:brand><![CDATA[BRAND1]]></g:brand>
</item>
<item>
<g:id>anID</g:id>
<g:inventory>5</g:inventory>
<g:description><![CDATA[Some Text]]></g:description>
<g:condition>new</g:condition>
<g:mpn>sku</g:mpn>
<g:title>Product Title</g:title>
<g:availability>in stock</g:availability>
<g:price>185.00 EUR</g:price>
<g:brand><![CDATA[BRAND2]]></g:brand>
</item>
<item>
<g:id>anID</g:id>
<g:inventory>5</g:inventory>
<g:description><![CDATA[Some Text]]></g:description>
<g:condition>new</g:condition>
<g:mpn>sku</g:mpn>
<g:title>Product Title</g:title>
<g:availability>in stock</g:availability>
<g:price>185.00 EUR</g:price>
<g:brand><![CDATA[BRAND2]]></g:brand>
</item>
............
I need to remove some nodes based on the brand value. My code currently looks like this:
$xmlstr = get_xml_from_url('urlToXMLFeed/xml/testfeed1.xml');
$xmlobj = new SimpleXMLElement($xmlstr);
$xmlobj->registerXPathNamespace("g", "http://base.google.com/ns/1.0");
$i = 0;
foreach($xmlobj->channel->item as $item)
{
$namespaces = $item->getNameSpaces(true);
// echo $namespaces;
$gbrand = $item->children($namespaces['g']);
$finalBrand = $gbrand->brand;
if(strcmp($finalBrand,"BRAND2") == 0)
{
unset($item);
}
$i ++;
}
//Format XML to save indented tree rather than one line and save
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xmlobj->asXML());
$dom->save('fileName.xml');
The newly generated XML still has the nodes with the BRAND2. Also, tried using this to remove the node
unset($xmlobj->channel->item->{$i});
But the second approach only removes the first occurrence of BRAND2.
Also tried the following:
$domElemsToRemove = array();
.......
if(strcmp($finalBrand,"BRAND2") == 0)
{
$domElemsToRemove[] = $item;
}
}
....
foreach( $domElemsToRemove as $domElement ){
$xmlobj->channel->removeChild($domElement);
}
But still the same result