Wednesday, 21 March 2012

PHP: Create variable names from XML element names

I needed to convert an xml file into an array. You can use an element name to name a variable using this example.

        $string = "<postcode>5253</postcode>";
        $xml = new SimpleXMLElement($string);

        $varname = $xml->getName();

        ${$varname} = trim($xml);

        echo($varname." is ".${$varname}."\n");
        echo($varname." is ".$postcode."\n");
 
Output:
 
postcode is 5253
postcode is 5253 

No comments: