Sunday, 11 January 2015

Extract specific XML data and save into new XML file

Question
Extracting text node from parent works great but how can i save it as a new XML file.

Answer
<?php
/* Convert an XML file into a SimpleXMLElement object  */
$xmlDoc     = simplexml_load_file("recipes.xml");
/* set variable as array  */
$storeArray = array();
/* for each <recipe> node use $recipe as key (Associative array) */
foreach ($xmlDoc->recipe as $recipe) {
    /* if child is not in array add it to our array */
    if (!in_array($recipe->category, $storeArray)) {
        array_push($storeArray, $recipe->category);
    }
}
/* remove any duplicates from array */
$result = array_unique($storeArray);
/* create a new SimpleXMLElement object */
$xml    = new SimpleXMLElement('<recipe></recipe>');
/* for each item in array use variable $category */
foreach ($result as $category) {
    /* add child node category with  text node $category */
    $details = $xml->addChild('category', $category);
}
/* change header type */
Header('Content-type: text/xml');
/* print to screen */
print($xml->asXML());
/* name to call our new file */
$xmlFileName = "categories.xml";
/* save our new file */
$xml->asXML($xmlFileName);
/* Open and prettify xml file */
$simplexml               = simplexml_load_file($xmlFileName);
$dom                     = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput       = true;
$dom->loadXML($simplexml->asXML());
$xml = new SimpleXMLElement($dom->saveXML());
$xml->saveXML($xmlFileName);
?> 

XML recipes.xml
Demo xml-new-xml.php

No comments:

Post a Comment