如何在PHP&中使用foreach XML(simplexml) [英] How to use foreach with PHP & XML (simplexml)
本文介绍了如何在PHP&中使用foreach XML(simplexml)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
知道PHP和XML的人吗?那请看看!
Anyone that knows PHP and XML out there? Then please have a look!
这是我的PHP代码:
<? $xml = simplexml_load_file("movies.xml");
foreach ($xml->movie as $movie){ ?>
<h2><? echo $movie->title ?></h2>
<p>Year: <? echo $movie->year ?></p>
<p>Categori: <? echo $movie->regions->region->categories->categorie ?></p>
<p>Country: <? echo $movie->countries->country ?></p>
<? } ?>
这是我的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<movies>
<movie>
<title>A movie name</title>
<year>2010</year>
<regions>
<region>
<categories>
<categorie id="3">Animation</categorie>
<categorie id="5">Comedy</categorie>
<categorie id="9">Family</categorie>
</categories>
<countries>
<country id="123">USA</country>
</countries>
</region>
</regions>
</movie>
<movie>
<title>Little Fockers</title>
<year>2010</year>
<regions>
<region>
<categories>
<categorie id="5">Comedy</categorie>
</categories>
<countries>
<country id="123">USA</country>
</countries>
</region>
</regions>
</movie>
</movies>
上面的代码的结果是:
<h2>A movie name</h2>
<p>Year: 2010</p>
<p>Category: Animation</p>
<p>Country: USA</p>
<h2>Little Fockers</h2>
<p>Year: 2010</p>
<p>Category: Comedy</p>
<p>Country: USA</p>
我希望它像这样(请参阅第一部电影中的类别):
I want it to be like this (see category on the first movie):
<h2>A movie name</h2>
<p>Year: 2010</p>
<p>Category: Animation, Comedy, Family</p>
<p>Country: USA</p>
<h2>Little Fockers</h2>
<p>Year: 2010</p>
<p>Category: Comedy</p>
<p>Country: USA</p>
注意:我也想知道如何获得单词之间的逗号,但最后一个单词没有逗号...
Note: Also I wonder how to get the comma between the words, but without a comma on the last word...
推荐答案
尝试一下.
<?php
$xml = simplexml_load_file("movies.xml");
foreach ($xml->movie as $movie) {
echo '<h2>' . $movie->title . '</h2>';
echo '<p>' . $movie->year . '</p>';
$categories = $movie->regions->region->categories->categorie;
while ($categorie = current($categories)) {
echo $categorie;
echo next($categories) ? ', ' : null;
}
echo '<p>' . $movie->countries->country . '</p>';
}
?>
这篇关于如何在PHP&中使用foreach XML(simplexml)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文