gholland85 Posted May 14, 2010 Share Posted May 14, 2010 Hello, I've converted an XML file to an array and I need to be able to loop through it and split up the 'name' field to separate the first and last name. I've worked out how to separate a single name in the array but can't work out how to loop through them all with foreach. Would anyone be able to help me out with this? Here is the code I have so far to explode the name for the first item in the array (0) include("xml2array.php"); $xml=xml2ary(file_get_contents('http://www.mypage.local/config/reviews.xml')); $xml = $xml[reviews][_c][Detail]; //splits first name and last name $xml[0][_a]["textbox5"] = explode(" ", $xml[0][_a]["textbox5"]); echo $xml[0][_a]["textbox5"][1] ; Any help much appreciated. Cheers, Greg. Quote Link to comment https://forums.phpfreaks.com/topic/201700-looping-through-an-array-for-foreach-and-breaking-up-strings-with-explode/ Share on other sites More sharing options...
gholland85 Posted May 14, 2010 Author Share Posted May 14, 2010 Ok, so I half worked it out. The code below seems to work however every 2nd row in the array in blank. Any ideas where I'm going wrong here? Thank you. foreach($xml as $v1) { foreach($v1 as $v2) { $exploded = explode(" ", $v2[textbox5]); $days = round(strtotime($v2["textbox13"]) - strtotime($v2["textbox10"])) / (60 * 60 * 24); $reviewname[$i] = array("first_name" => $exploded[0], "last_name" => $exploded[1], "nights_stayed" => $days ); $i++; } } Quote Link to comment https://forums.phpfreaks.com/topic/201700-looping-through-an-array-for-foreach-and-breaking-up-strings-with-explode/#findComment-1058510 Share on other sites More sharing options...
Psycho Posted May 14, 2010 Share Posted May 14, 2010 Can't really say without seeing the input data, but I would guess that some "records" do not have the 'textbox5' key (you know you should enclose the string key name in quotes, right?). Also, you don't need to use $i, just use []. Try this: foreach($xml as $v1) { foreach($v1 as $v2) { if(isset($v2['textbox5'])) { $name = explode(" ", $v2['textbox5']); $days = round(strtotime($v2['textbox13']) - strtotime($v2['textbox10'])) / (60 * 60 * 24); $reviewname[] = array("first_name" => $name[0], "last_name" => $name[1], "nights_stayed" => $days ); } } } Quote Link to comment https://forums.phpfreaks.com/topic/201700-looping-through-an-array-for-foreach-and-breaking-up-strings-with-explode/#findComment-1058527 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.