Hi,
I'm working on a project and I've run into a problem and I can't seem to figure out how to fix it or even what is wrong no matter how much I google. I have data in an xml file that I need to read and use to create an array.
Here is the XML (food.xml):
<?xml version="1.0" encoding="UTF-8"?>
<Foods>
<Food type='fruit' color='yellow'>banana</Food>
<Food type='vegetable' color='green'>lettuce</Food>
<Food type='meat' color='red'>beef</Food>
</Foods>
Here is my code to work with the XML (xml_data.php)
<?php
$file = 'food.xml';
$xml = simplexml_load_file($file);
$food = array();
// Example variables
$type = 'grain';
$name = 'corn';
// Adds example variables to array
$food->key = $type;
$food[$type] = $name;
// Displays XML data and add to array
for($i=0;$i<sizeof($xml);$i++){
// Assigns XML data to variables
$type = $xml->Food[$i][type];
$name = $xml->Food[$i];
// Prints variables to see that XML data is actually read
echo '(Inside for loop) '.$type.'...'.$name.'<br>';
// Assigns variables to array
$food->key = $type;
$food[$type] = $name;
}
echo '<br>Size of array is '.sizeof($food).'<br><br>';
// Prints each entry in the array
foreach($food as $key=>$value){
echo '(Inside foreach) Key is '.$key.'<br>';
echo '.....and Value is '.$value.'<br>';
}
?>
The example variables when placed into the array work but when I use the same method to place the XML variables into the array it does not.
Why does this not work? How can I get it to work?
I'm attaching files as well, just in case. Both files are saved in the same directory.
Thanks for any help.
food.xml
xml_data.php