简体   繁体   English

PHP-xml中的两个相同节点

[英]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. 我无法编辑XML,因此需要解决以下问题。 How to say to PHP that I need to show the second node called CATEGORY and not the first one. 怎么说PHP,我需要显示第二个名为CATEGORY的节点,而不是第一个。 In my example I have the output 在我的示例中,我有输出

Books
Books

And I need: 我需要:

Books | Novel
Books | Sci-fi

Thank you! 谢谢!

This is what you are looking for (note the [1]): 这是您要寻找的(请注意[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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM