如果您事先不知道电影的类型,您可以:
- 从 XML 数据中提取所有类型
- 让它们独一无二,因为它们可能会出现多次(可能有一种方法可以使用 XPath 做到这一点;我不知道,所以我会使用
array_unique
)
- 使用@Mark 提议的内容迭代这些类型。
这样的事情可能会做:
$xml = simplexml_load_string($xmlData);
$typesListXml = $xml->xpath('interesting/type');
var_dump($typesListXml); // var_dump #1
if (!empty($typesListXml)) {
$typesList = array();
foreach ($typesListXml as $typeXml) {
$typesList[] = (string)$typeXml;
}
var_dump($typesList); // var_dump #2
$typesList = array_unique($typesList);
var_dump($typesList); // var_dump #3
$moviesForType = array();
foreach ($typesList as $type) {
$rawData = $xml->xpath('interesting[type="' . $type . '"]');
if (!empty($rawData)) {
foreach ($rawData as $rawMovie) {
$moviesForType[$type][] = $rawMovie->name . ' - ' . $rawMovie->character;
}
}
}
var_dump($moviesForType); // var_dump #4
// Up to you to present $moviesForType the way you want ;-)
}
为了让事情更容易理解,这里是 var_dump 的输出:
var_dump #1:
array
0 =>
object(SimpleXMLElement)[2]
string 'Movie' (length=5)
1 =>
object(SimpleXMLElement)[3]
string 'Movie' (length=5)
2 =>
object(SimpleXMLElement)[4]
string 'Book' (length=4)
var_dump #2:
array
0 => string 'Movie' (length=5)
1 => string 'Movie' (length=5)
2 => string 'Book' (length=4)
var_dump #3:
array
0 => string 'Movie' (length=5)
2 => string 'Book' (length=4)
var_dump #3:
array
'Movie' =>
array
0 => string 'Casino Royale - James Bond' (length=26)
1 => string 'Bourne Identity - Jason Bourne' (length=30)
'Book' =>
array
0 => string 'Shantaram - Lindsay Ford' (length=24)
现在,由您决定以您想要的方式呈现这些数据;一个双 foreach 循环构造<ul>
和<li>
标签可能会做;-)