Extract Text Node from parent ignoring duplicates

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

Question

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?

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

Demo xtract-node-xml.php

AnonymousIan.J.Gough

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,
Ian.J.Gough

protected by copyscape duplicate content check

Categories


Powered by Banner Bar 125