Michal Vlasák
Michal Vlasák

Reputation: 247

PHP - Two same nodes in xml

I have the following code:

<?php
    $str = '<?xml version="1.0" encoding="utf-8"?>
            <ROOT>
                <ITEM>
                    <TITLE>Title1</TITLE>
                    <CATEGORY>Books</CATEGORY>
                    <CATEGORY>Books | Novel</CATEGORY>
                </ITEM>
                <ITEM>
                    <TITLE>Title2</TITLE>
                    <CATEGORY>Books</CATEGORY>
                    <CATEGORY>Books | Sci-fi</CATEGORY>
                </ITEM>
            </ROOT>';

    $xml = simplexml_load_string($str);

    $s_xml = $xml->xpath("/ROOT/ITEM");
    foreach($s_xml as $s_cat){
        $cat_group = htmlspecialchars($s_cat->CATEGORY);
        echo $cat_group."<BR />";
    }
?>

I can't edit the XML so I need to solve the folowing problem. How to say to PHP that I need to show the second node called CATEGORY and not the first one. In my example I have the output

Books
Books

And I need:

Books | Novel
Books | Sci-fi

Thank you!

Upvotes: 1

Views: 34

Answers (1)

BobbyTables
BobbyTables

Reputation: 4685

This is what you are looking for (note the [1]):

 $cat_group = htmlspecialchars($s_cat->CATEGORY[1]);

It takes the second item in the array of category elements

You can always look at your elements like this, to figure out how the structure looks:

print_r($s_cat->CATEGORY);

Upvotes: 1

Related Questions