How to use foreach with PHP & XML (simplexml)

2019-01-19 19:09发布

Anyone that knows PHP and XML out there? Then please have a look!

This is my PHP code:

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

<? } ?>

This is mys XML file:

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

The outcome of the code above is:

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

7条回答
The star\"
2楼-- · 2019-01-19 19:59
<?php
$cat_out='';
foreach($movie->regions->region->categories->categorie as $cat){
 $cat_out.= $cat.',';
}
echo rtrim($cat_out,',');
?>
查看更多
登录 后发表回答