Saturday, 10 January 2015

Extract Text Node from parent ignoring duplicates

Each recipe in recipes.xml is in a category and i want to print a list of the category's used without having lots of duplicates how can i do that?

/* 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);
/* for each item in array echo as $category */
foreach ($result as $category) {
    echo $category . "<br>";

Demo xtract-node-xml.php

No comments:

Post a Comment