PHP program to generate and parse (read) XML.

xml.rar

generate-xml.php

<?php

$data =
array(
	array("raj","mehta","99999","raj@raj.com"),
	array("rahul","bajaj","88888","rahul@rahul.com"),
);

$str = "<contact_data>";

foreach($data as $key=>$val)
{
	$str .= "<person>";
	$str .= "<fname>{$val[0]}</fname>";
	$str .= "<lname>{$val[1]}</lname>";
	$str .= "<phone>{$val[2]}</phone>";
	$str .= "<email>{$val[3]}</email>";
	$str .= "</person>";
}

$str .= "</contact_data>";

$fp = fopen("contacts.xml", "w+");
fwrite($fp, $str);

?>

read-xml.php

<?php

$xml_file = "contacts.xml";
$xsd_file = "contacts.xsd";

//Validate XML against XSD
$xml = new DOMDocument();
$xml->load($xml_file);
if($xml->schemaValidate($xsd_file))
{
	echo "Validated";

	$xml = simplexml_load_file($xml_file);
	print "<pre>";
	print_r($xml);
	foreach($xml->person as $person)
	{
		echo $person->fname;
		echo $person->lname;
		echo $person->phone;
		echo $person->email;
		echo "<br />";
	}
}
else
{
	echo "Not valid";
}

?>

contacts.xsd

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="contact_data">
  <xs:complexType>
    <xs:sequence>      
      <xs:element name="person" maxOccurs="unbounded">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="fname" type="xs:string"/>
            <xs:element name="lname" type="xs:string"/>
            <xs:element name="phone" type="xs:string"/>
            <xs:element name="email" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

</xs:schema>