任何知道PHP和XML的人都有嗎?那麼請看看!如何在PHP和XML中使用foreach(simplexml)
這是我的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>
<? } ?>
這是MYS 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>
我想它就像這樣(參見第一部電影類別):
<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>
注:另外我想知道如何得到詞之間的逗號,但沒有對最後一個字一個逗號......
+1剝出後面的逗號。 `while($ categorie = current($ movie - > ...-> categorie))`和`echo next($ movie - > ...-> categorie)? ',':'';`也可以。 – Dan 2011-01-09 04:18:04