好的,这是我的困境。我正在寻找一种使用PHP中的 SimpleXML 来整合组中数据的方法。这就是我的意思。
假设我有一个看起来像这样的xml:
<favorites>
<interesting>
<type>Movie</type>
<character>James Bond</character>
<name>Casino Royale</name>
</interesting>
<interesting>
<type>Movie</type>
<character>Jason Bourne</character>
<name>Bourne Identity</name>
</interesting>
<interesting>
<type>Book</type>
<character>Lindsay Ford</character>
<name>Shantaram</name>
</interesting>
</favorites>
现在这就是我想要的样子:
电影
图书
请帮帮我!!如果有什么事情让人困惑,请告诉我。
答案 0 :(得分:4)
如果你事先不知道电影的类型,你可以:
array_unique
)
这样的事情可能会这样:
$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)
现在,您可以按照自己的方式呈现这些数据;构建<ul>
和<li>
代码的双foreach循环可能会执行; - )
答案 1 :(得分:1)
我相信您正在寻找Xpath:
$xmlData = '<favorites>...</favorites>';
$xml = simplexml_load_string($xmlData);
$arrMovies = $xml->xpath('interesting[type="Movie"]');
$arrBooks = $xml->xpath('interesting[type="Book"]');
然后你可以遍历$ arrMovies和$ arrBooks并打印出你需要的东西:
foreach($arrMovies as $movie) {
echo $movie->name;
}