Search code examples
phpxmlelementappendchild

Add child for each element in XML using PHP


I've never worked with XML using PHP and I can't seem to work around this easy (I think) problem.

Here's my XML:

<StockFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Stock>
        <Prod>M</Prod>
    </Stock>
    <Stock>
        <Prod>Y</Prod>
    </Stock>
    <Stock>
        <Prod>N</Prod>
    </Stock>
</StockFile>

What I want to achieve:

<StockFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <Stock>
                <Prod>M</Prod>
                <price>Example</price>
        </Stock>
        <Stock>
                <Prod>Y</Prod>
                <price>Example</price>
        </Stock>
        <Stock>
                <Prod>N</Prod>
                <price>Example</price>
        </Stock>
</StockFile>

And here's my code:

private static function appendPrice()
{
     $xml = simplexml_load_file("file.xml");

     foreach ($xml->Stock as $stock)
     {
         echo $stock->Prod;
         $stock->addChild('price', 'Example');
     }
}

Even though it's an easy question, I can't seem to work around it, I get no response whatsoever out of it, the echo is fine but the child is not added. What am I doing wrong?


Solution

  • You're not saving the file after the changes:

    private static function appendPrice()
    {
         $xml = simplexml_load_file("file.xml");
    
         foreach ($xml->Stock as $stock)
         {
             echo $stock->Prod;
             $stock->addChild('price', 'Example');
         }
    
         $xml->saveXML('file.xml');
    
    }
    

    saveXML