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

Posted By: Ian on Jan 30, 2015 in PHP, Snippets, XML


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


Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

leave a comment

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,

protected by copyscape duplicate content check


Powered by Banner Bar 125