Anyone that knows PHP and XML out there? Then please have a look!
This is my PHP code:
Year:
Categori:
Country:
This is mys XML file:
A movie name
2010
Animation
Comedy
Family
USA
Little Fockers
2010
Comedy
USA
The outcome of the code above is:
A movie name
Year: 2010
Category: Animation
Country: USA
Little Fockers
Year: 2010
Category: Comedy
Country: USA
I want it to be like this [see category on the first movie]:
A movie name
Year: 2010
Category: Animation, Comedy, Family
Country: USA
Little Fockers
Year: 2010
Category: Comedy
Country: USA
Note: Also I wonder how to get the comma between the words, but without a comma on the last word...
asked Jan 9, 2011 at 4:02
0
Try this.
answered Jan 9, 2011 at 4:11
JonahJonah
9,8915 gold badges44 silver badges79 bronze badges
1
this is how you use foreach with an simplexmlElement:
$xml = simplexml_load_file["movies.xml"];
foreach [$xml->children[] as $children] {
echo $children->name;
}
answered Nov 6, 2013 at 12:59
answered Jan 9, 2011 at 4:20
You need to iterate through the categorie
elements too, in the same way you've iterated through
movies
.
echo '';
foreach[$movie->regions->region->categories->categorie as $categorie]{
echo $categorie . ', ';
}
echo '
';
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] ? ', ' : '';
}
answered Jan 9, 2011 at 4:09
Dan LuggDan Lugg
19.7k18 gold badges107 silver badges172 bronze badges
Categori:
answered Jan 9, 2011 at 4:10
dqhendricksdqhendricks
18.6k10 gold badges48 silver badges82 bronze badges
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:
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].
answered Jan 9, 2011 at 4:14
prodigitalsonprodigitalson
59.5k9 gold badges97 silver badges112 bronze badges
Try This one
$xml = ... // Xml file data
$Json = Xml_to_Json[$xml];
$array = json_decode[$Json,true];
echo ''; print_r[$array];
foreach [$array as $key => $value] {
foreach [$value as $key1 => $value1] {
echo ''.$value1['title'].'
Year: '.$value1['year'].'
Category: ';
foreach [$value1['regions']['region']['categories']['categorie'] as $categoriekey => $categorie] {
echo $categorie.' ';
}
echo 'Animation
Country: '.$value1['regions']['region']['countries']['country'].'
';
}
}
function Xml_to_Json[$array]{
$xml = simplexml_load_string[$array, "SimpleXMLElement", LIBXML_NOCDATA];
$json = json_encode[$xml];
return $json;
}
answered Jun 25, 2016 at 12:32
Ajay KumarAjay Kumar
1,30412 silver badges22 bronze badges
2