0

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

user580950
  • 3,558
  • 12
  • 49
  • 94

1 Answers1

1

You can use DOM with SimpleXML.

Here's what you should do:

  1. Use xpath() to run an xpath query that picks out all the Product tags. This should return you an array of SimpleXMLElements representing each Product tag.

  2. Use xpath() again to select from each Product tag the ProductCode and ProductName and get their contents. Create your url and save it to a variable.

  3. Use xpath() to select the StockStatus tag.

  4. Using DOM's dom_import_simplexml(), convert the SimpleXMLElement StockStatus tags to a DOMElement.

  5. Create the ProductURL element using DOM's createElement() and insert the url we created before.

  6. Insert it before StockStatus using DOM's insertBefore().

This question should show you how to do the conversion to a DOMElement and finally do the insertion.

Community
  • 1
  • 1
F21
  • 32,163
  • 26
  • 99
  • 170
  • I tried till step 3 and it works great i did this $element = $dom->createElement('ProductURL', 'This is the root element!'); // We insert the new element as root (child of the document) $dom->appendChild($element); but i am not sure how to create that producr url dynamically like http://abc.com/-p/.htm – user580950 Jul 14 '12 at 09:56
  • your first step doesnt work i tried using the following it doesnt picks out the product tags $result = $xml->xpath('/All_Products/Product'); while(list( , $node) = each($result)) { echo '/a/b/c: ',$node,"\n"; } – user580950 Jul 14 '12 at 12:23