Elwood Posted August 14, 2014 Share Posted August 14, 2014 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 Quote Link to comment Share on other sites More sharing options...
Solution Ch0cu3r Posted August 15, 2014 Solution Share Posted August 15, 2014 You need to change these lines $type = $xml->Food[$i][type]; $name = $xml->Food[$i]; so the values are returned as strings not objects $type = (string) $xml->Food[$i]['type']; $name = (string) $xml->Food[$i]; Also remove this from lines 12 & 25 $food->key = $type; $food is an array not an object so you cant set properties to an array. Remove them it is not needed. Quote Link to comment Share on other sites More sharing options...
Elwood Posted August 15, 2014 Author Share Posted August 15, 2014 THANK YOU!!! Thank you so much for your help. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.