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($movie->regions->region->categories->categorie as $category) { ?>
<p>Categori: <?= $category ?></p>
<? } ?>
function categoryList(SimpleXmlElement $categories){
$cats = array();
foreach($categories as $category){
$cats[] = (string) $category;
}
return implode(', ', $cats);
}
Then you can jsut call it from your loop like:
<? echo categoryList($movie->regions->region->categories); ?>
Using an array and implode
removes the need for logic of counting and detecting the last category.
Isolating it in a function makes it easier to maintain and is less confusing than nesting the loop (though admittedly nested loops arent that confusing).
this is how you use foreach with an simplexmlElement:
$xml = simplexml_load_file("movies.xml");
foreach ($xml->children() as $children) {
echo $children->name;
}
Try this.
<?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
$cat_out='';
foreach($movie->regions->region->categories->categorie as $cat){
$cat_out.= $cat.',';
}
echo rtrim($cat_out,',');
?>
You need to iterate through the categorie
elements too, in the same way you've iterated through movies
.
echo '<p>';
foreach($movie->regions->region->categories->categorie as $categorie){
echo $categorie . ', ';
}
echo '</p>';
You'll probably want to trim the trailing ,
as well.
The method mentioned in my comment:
$categories = $movie->regions->region->categories->categorie;
while($category = current($categories)){
echo $category . next($categories) ? ', ' : '';
}