I want to build an XML document in PHP.
I chose DOMDocument, and i know i have to use methods like createElement
, createTextNode
, appendChild
, etc. to build my XML.
This is how i generated the xml with just one node containing vehicle information:
<?php
$doc = new DOMDocument ( '1.0', 'utf-8' );
$vehicles = $doc->createElement ( "Vehicles" );
$vehicle = $doc->createElement("Vehicle");
$vehicle_num = $doc->createElement("Number");
$vehicle_desc = $doc->createElement("Description");
$vehicle_year = $doc->createElement("Year");
$vehicle_make = $doc->createElement("Make");
$vehicle_model = $doc->createElement("Model");
$vehicle_color = $doc->createElement("Color");
$vehicle_num->appendChild($doc->createTextNode("AW2CM31Y8"));
$vehicle_year->appendChild($doc->createTextNode("2013"));
$vehicle_make->appendChild($doc->createTextNode("VOLKSWAGEN"));
$vehicle_model->appendChild($doc->createTextNode("NEW BEETLE"));
$vehicle_color->appendChild($doc->createTextNode("Black"));
$vehicle_desc->appendChild($vehicle_year);
$vehicle_desc->appendChild($vehicle_make);
$vehicle_desc->appendChild($vehicle_model);
$vehicle_desc->appendChild($vehicle_color);
$vehicle->appendChild($vehicle_num);
$vehicle->appendChild($vehicle_desc);
$vehicles->appendChild($vehicle);
$doc->appendChild ( $vehicles );
header ( "Content-type: text/xml" );
echo $doc->saveXML ();
But, what if i want to build an xml with say 100 nodes containing not only vehicle information, but also other nodes above and below it. This process would be too laborious.
So, is there an easy way of creating nodes and adding values to them in xml with php? I am concerned with the number of lines of code that i am supposed to write.