Load XML File in PHP and add Child if not exists

446 Views Asked by At

i want to load XML data into my php file with address data. Each address should also have coordinates - if not they should be added. So i am doing the following:

        $xmlDatei = "AddressData.xml";
        $xml = simplexml_load_file($xmlDatei);

        for($i=0,$size=count($xml);$i<$size;$i++){

            if($xml->RECORD[$i]->ADDRESS->LAT != NULL){
                //get lat and lng stuff here...

                $lat = .......
                $lng = .......


                echo "lat: " . $lat; // Test echo WORKING
                echo "lng: " . $lng;

                // Now i want to add the data to the xml
                $xml->RECORD[$i]->ADDRESS->addAttribute('LAT', $lat);
                $xml->RECORD[$i]->ADDRESS->addAttribute('LNG', $lng);

                $xml->saveXML();
            }

            // Test echo NOT WORKING
            echo $xml->RECORD[$i]->ADDRESS->LAT;
            echo $xml->RECORD[$i]->ADDRESS->LNG;
        }

So it seems like the addAttribute is not working properly here.

What am I doing wrong???

2

There are 2 best solutions below

2
On BEST ANSWER

Your echo is looking for a child element called LAT:

echo $xml->RECORD[$i]->ADDRESS->LAT;

But you have added an attribute, so you need to use different syntax:

echo $xml->RECORD[$i]->ADDRESS['LAT'];
1
On

You are adding attributes to the ADDRESS tag, not nodes.

Try this:

echo $xml->RECORD[$i]->ADDRESS['LAT'];
echo $xml->RECORD[$i]->ADDRESS['LNG'];