Search code examples
phparraysxmlsimplexml

SimpleXml foreach : ignore element


        <?php

    $xml = "<articles>
    <article id=\"18357302\">
    <articleCategories>
    <articleCategory id=\"default\"/>
    <articleCategory id=\"66607\"/>
    </articleCategories>
    </article>
    </articles>";

    $feed = simplexml_load_string($xml);

    $items = $feed->article;
    foreach ($items as $article) {

    //  $categorie = $article->articleCategories->articleCategory[id];
    $categories = $article->articleCategories;
    print_r($categories);
    echo "<br>print_r indeed returns an array, but impossible to echo it using foreach!!!<br>";
    foreach ($categories->id as $category) {
if ($category != "default") {
        echo $category;
}
    }
    }
    ?>

not sure what i am doing wrong, i am just trying to find a way to remove the part with the default value inside articlesCategories

<articleCategory id=\"default\"/>

The script needs to ignore this part and just use the next articleCategory from the XML file, and i would prefer to avoid removing it with regex


Solution

  • The script iterates over articleCategories tag. But it needs to iterate over articleCategory tag.

    The following changes will be enough.

    foreach ($categories->articleCategory as $category) {
        if ($category["id"] != "default") {
            echo $category["id"];
        }
    }