gpt4 book ai didi

php - 如何在 PHP 和 XML 中使用 foreach(simplexml)

转载 作者:可可西里 更新时间:2023-11-01 12:41:24 26 4
gpt4 key购买 nike

有人了解 PHP 和 XML 吗?那就请看吧!

这是我的 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>

我希望它是这样的(参见第一部电影的类别):

<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>

注意:另外我想知道如何在单词之间获取逗号,但最后一个单词没有逗号......

最佳答案

试试这个。

<?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 - 如何在 PHP 和 XML 中使用 foreach(simplexml),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4637617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com