phpxmlsimplexmladdattribute

Load XML File in PHP and add Child if not exists


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???


Solution

  • 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'];