Sunday, 11 January 2015

Extract and split node by comma and save to new XML file

Using Extract specific xml data and save to new xml i can extract specific nodes but what if the text node is a CSV.  As some recipes can be in more than 1 category.

/* Convert an XML file into a SimpleXMLElement object  */
$xmlDoc     = simplexml_load_file("test.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);
/* separate array by , (array to string) */
$arrayString  = implode(",", $storeArray);
/* break string into array separating by , (string to array) ) */
$stringArray  = explode(',', $arrayTring);
/* take each array value and trim whitespace */
$trimmedArray = array_map('trim', $stringArray);
/* remove any duplicates from array */
$result       = array_unique($trimmedArray);
/* for each item in array echo as $category */
foreach ($result as $category) {
    echo $category . "<br>";

XML multi-category.xml
Demo split-node-xml.php

No comments:

Post a Comment