Reputation: 6779
I have this xml file:
<?xml version="1.0"?>
<products>
<product>
... some nodes
</product>
<product>
... some nodes
</product>
<product>
... some nodes
</product>
</products>
And i wrote this php code:
<?php
....
....
$xml=simplexml_load_file("myfile.xml") or die("Error: Cannot create object");
foreach ($xml->xpath("/products/product") as $prod)
{
$xmlname = $xml->addChild("name",$name);
$xmlid = $xml->addChild("id",$id);
$xmlprice = $xml->addChild("price",$price);
}
$xml->asXML ("result_file.xml");
?>
This works, but not as I want. It creates the file 'result_file.xml' with new nodes: $name,$id and $price. The problem is that all these nodes are inserted at the end of the xml file like this:
<?xml version="1.0"?>
<products>
<product>
... some nodes
</product>
<product>
... some nodes
</product>
<product>
... some nodes
</product>
<name>$name</name>
<id>$id</id>
<price>$price</price>
<name>$name</name>
<id>$id</id>
<price>$price</price>
<name>$name</name>
<id>$id</id>
<price>$price</price>
</products>
But I'd like to insert all these nodes after their product node. For example, i want to obtain:
<?xml version="1.0"?>
<products>
<product>
<name>$name</name>
<id>$id</id>
<price>$price</price>
... some nodes
</product>
<product>
<name>$name</name>
<id>$id</id>
<price>$price</price>
... some nodes
</product>
<product>
<name>$name</name>
<id>$id</id>
<price>$price</price>
... some nodes
</product>
</products>
Upvotes: 0
Views: 38
Reputation: 311
I think the problem you are having here is that you are adding the child XML elements to the root $xml.
Looking at your code, if you were to change the following:
foreach ($xml->xpath("/products/product") as $prod) {
$xmlname = $prod->addChild("name",$name);
$xmlid = $prod->addChild("id",$id);
$xmlprice = $prod->addChild("price",$price);
}
$xml->asXML ("result_file.xml");
That should work.
$prod is seen as an instance of every <product>
Upvotes: 4