简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM