The first thing that comes to mind is that you have got code-repetition. You perhaps want to reduce that. This can be done by moving duplicate code into a function of it's own.
To do that fast, PHP has closures. Let's line that up:
You have a collection of vehicles and each vehicle just has properties and values. So you add a property to a vehicle. BTW, createElement
does take a text already as value, so that you don't need to create the text-nodes. So let's wrap the duplicate code into functions and then just call these functions to create the XML. That already - through parametrization - shows your structure. Just differ between the definitions of the functions (first part) and the apply of those (second part):
<?php
/**
* Create XML Document with PHP in an easy way
*
* @link http://stackoverflow.com/q/19702911/367456
*/
/**
* @param DOMNode $node
* @return DOMDocument
*/
$doc = function (DOMNode $node = NULL) {
return $node ? ($node->ownerDocument ? : $node) : new DOMDocument();
};
/**
* @param DOMElement $element
* @param string $property
* @param string $text
* @return DOMElement the element the proeprty was added to
*/
$prop = function (DOMElement $element, $property, $text) {
return $element->appendChild(
$element->ownerDocument->createElement($property, $text)
);
};
/**
* @param DOMNode $element
* @param string $name
* @return DOMElement
*/
$element = function (DOMNode $element, $name) use ($doc) {
return $element->appendChild(
$doc($element)->createElement($name)
);
};
So after all those functions have been defined, on to the second part:
$prop(
$vehicle = $element(
$vehicles = $element(
$doc()
, 'Vehicles'
)
, 'Vehicle'
)
, "Number"
, "AW2CM31Y8"
);
$prop(
$vehicle
, "Year"
, "2013"
);
$prop(
$vehicle
, "Make"
, "VOLKSWAGEN"
);
$prop(
$vehicle
, "Model"
, "NEW BEETLE"
);
$prop(
$vehicle
, "Color"
, "Black"
);
Et voila. This has revealed some structure. Code-duplication has been removed as well. The only thing left is to finally echo the result out:
header("Content-type: text/xml");
echo $doc($vehicles)->saveXML();
If you look at the code you can even read that it literally does reverse the data-structure to create the XML. So next thing would be to make use of some kind of traversal, but that needs the definition of a data-structure first, not only the definition of the code-structure as it has been done so far (and which should already be of use for you).
Online Example: https://eval.in/59090