I am using SimpleXML to load a remote XML
My PHP code looks like below
$xml = simplexml_load_file('http://www.abc.om/xml.php');
foreach( $xml as $Product )
{
echo 'ProductCode: '.$Product->ProductCode.'<br />';
echo 'ProductName: '.$Product->ProductName.'<br />';
}
MY XML looks like below
<All_Products>
<Product>
<ProductCode>9978H</ProductCode>
<ProductName>abc with Buckle in aBlack</ProductName>
<StockStatus>2</StockStatus>
</Product>
</All_Products>
Product tags are repeated as there are many products
after reading that XMLfeed the XML feed should display with some ammends that is before
<StockStatus> tag it should add a tag
<ProductURL><ProductURL>
and that tag should display like
<ProductURL>http://abc.com/abc with Buckle in aBlack-p/9978H.htm<ProductURL>
That means each ProductURL should be appended as
<ProductURL>http://abc.com/<ProductName>-p/<ProductCode>.htm<ProductURL>
The final XML to display will look like
<All_Products>
<Product>
<ProductCode>9978H</ProductCode>
<ProductName>abc with Buckle in aBlack</ProductName>
<ProductURL>http://abc.com/abc with Buckle in aBlack-p/9978H.htm<ProductURL>
<StockStatus>2</StockStatus>
</Product>
</All_Products>
So my questions are
1) Do i have to read all the elements of the Product tag in the foreach( $xml as $Product ) loop and then append ProductURL element or is there any shortcut to do it
2) Once this data is ready how do i again display the data in XML format
You can use DOM with SimpleXML.
Here’s what you should do:
Use xpath() to run an xpath query that picks out all the
Producttags. This should return you an array ofSimpleXMLElements representing eachProducttag.Use xpath() again to select from each
Producttag theProductCodeandProductNameand get their contents. Create your url and save it to a variable.Use xpath() to select the
StockStatustag.Using DOM’s dom_import_simplexml(), convert the
SimpleXMLElementStockStatustags to aDOMElement.Create the
ProductURLelement using DOM’s createElement() and insert the url we created before.Insert it before
StockStatususing DOM’s insertBefore().This question should show you how to do the conversion to a
DOMElementand finally do the insertion.