Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Created April 24, 2012 06:45
Show Gist options
  • Select an option

  • Save lamprosg/2477177 to your computer and use it in GitHub Desktop.

Select an option

Save lamprosg/2477177 to your computer and use it in GitHub Desktop.
PHP simplexml
<?xml version="1.0"?>
<users>
<user>
<firstname>John</firstname>
<surname>Brady</surname>
<address>1 Bunch St</address>
<city>Downtown</city>
<country>America</country>
<contact>
<phone type="mobile">4444 4444</phone>
<url>http://phpro.org</url>
<email>brady@bunch.example.com</email>
</contact>
</user>
<user>
...........
</user>
</users>
<?php
try
{
/*** a new dom object ***/
$dom = new domDocument;
/*** make the output tidy ***/
$dom->formatOutput = true;
/*** create the root element ***/
$root = $dom->appendChild($dom->createElement( "users" ));
/*** create the simple xml element ***/
$sxe = simplexml_import_dom( $dom );
/*** add a user node ***/
$user = $sxe->addchild("user");
/*** add a firstname element ***/
$user->addChild("firstname", "John");
/*** add a surname element ***/
$user->addChild("surname", "Brady");
/*** add address element ***/
$user->addChild("address", "1 Bunch St");
/*** add the city element ***/
$user->addChild("city", "Downtown");
/*** add the country ***/
$user->addChild("country", "America");
$contact = $user->addChild("contact");
$phone = $contact->addChild("phone", "4444 4444");
/*** add an attribute to the phone element ***/
$phone->addAttribute("type", "mobile")
$contact->addChild("url", "http://phpro.org");
$contact->addChild("email", "brady@bunch.example.com");
$sxe->asXML("address.xml");
}
catch( Exception $e )
{
echo $e->getMessage();
}
?>
<?php
/*** create a SimpleXML object ***/
if( ! $xml = simplexml_load_file('address.xml') )
{
echo "Unable to load XML file";
}
else
{
//access the firstname, surname, and phone number and the attribute of the second user.
echo $xml->user[1]->firstname.' '.$xml->user[1]->surname.'<br />';
echo $xml->user[1]->contact->phone;
echo $xml->user[1]->contact->phone->attributes();
}
?>
@lamprosg
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment