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
我无法编辑XML,所以我需要解决以下问题。如何对PHP说我需要显示名为CATEGORY的第二个节点而不是第一个节点。在我的例子中,我有输出
Books
Books
And I need:
我需要:
Books | Novel
Books | Sci-fi
Thank you!
1 个解决方案
#1
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);
#1
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);