Wednesday, 1 July 2009

Create Strings from XML using PHP.

This code uses the simplexml function included in PHP 5.

It's purpose is to create string variables from XML.

It only works properly as long as every xml tag is unique, if a tag is repeated it will overwrite and be useless to you.

here's an example of what it does,

Sample XML:
<?xml version="1.0" encoding="utf-8" ?>
<newsignup>
<username>John Smith</username>
<password>p455w0rd</password>
</newsignup>

the code would create two variables $username and $password, each containing the values from the XML, so print $username would display "John Smith"

Here's the PHP -
$xml = simplexml_load_string($data);

foreach($xml->children() as $child)
{
$Name = $child->getName();
$$Name = $child;
}

this code is presuming you've stored the XML data in a variable called $data. If the XML is a file you can replace the first line with this:
$xml = simplexml_load_file("test.xml");

to load your external xml file.

No comments:

Post a Comment