如何读取具有两个属性的标签


How to read a tag with two attributes

我有一个带有特殊标签的xml rss,我不知道如何阅读第二部分,在这种情况下是子类别

XML RSS:

<?xml version="1.0" encoding="UTF-8"?>
<channel>
    <category text="Category">
    <category text="Subcategory"/>
    </category>
</channel>
</rss>

PHP

//this gives the category
$category = $feed->channel->category->attributes(); 
echo $category . '<br>';
//I tried this but only gives category and I need subcategory too
foreach ($feed->channel->category->attributes() as $item) { 
    echo $item . '<br>';
}

这是因为您有两个类别元素,而不是两个属性;并且一个类别元素是另一类别元素的嵌套元素

foreach ($feed->channel->category as $category) { 
    foreach($category->attributes() as $attribute) {
        echo $attribute . '<br>';
    }
    foreach ($category->category as $subcategory) { 
        foreach($subcategory->attributes() as $attribute) {
            echo $attribute . '<br>';
        }
    }
}

编辑

如果您的代码段语法正确,正确缩进,则可能更容易理解

<?xml version="1.0" encoding="UTF-8"?>
<rss>
    <channel>
        <category text="Category">
            <category text="Subcategory"/>
        </category>
    </channel>
</rss>

因此,category元素可以有"子"元素,也称为category