I am parsing the xml like following:
$result = ' <sms> <status>0</status> <message> <contact_lists> <contact_list><cl_id>11111</cl_id><phone>999999999</phone><name>Neu</name></contact_list> <contact_list><cl_id>222222</cl_id><phone>888888888</phone><name>Alt</name></contact_list> </contact_lists> </message> </sms>'; $xml = simplexml_load_string($result, "SimpleXMLElement", LIBXML_NOCDATA); $json = json_encode($xml); $array = json_decode($json,true); $contact_lists = $array['contact_lists']['contact_list'];
A
sometimes the array look like this, which is works.
Array ( [status] => 0 [message] => Array ( ) [contact_lists] => Array ( [contact_list] => Array ( [0] => Array ( [cl_id] => 11111 [phone] => 999999999 [name] => Neu ) [1] => Array ( [cl_id] => 222222 [phone] => 888888888 [name] => Alt ) ) ) )
B
but sometime if the array has only one contact_list, it will look like following
Array ( [status] => 0 [message] => Array ( ) [contact_lists] => Array ( [contact_list] => Array ( [cl_id] => 11111 [phone] => 999999999 [name] => Neu ) ) )
when i use $contact_lists
in foreach loop it works with A
since there are multiple array keys like 0,1,2,etc… but with B
it shows error Warning: Illegal string offset 'name' etc..
since there are no array key like 0,1,2,etc…
so parsing the xml is automatically removing the key numbering which causing the the issue.
1- is there a way to keep the key numbering if only one array?
2- tried to use if (count($contact_lists) >= 1) {
, but its not working as well..
Any idea for a workaround to solve such issue ?
SOLUTION:
$contact_lists_found = isset($array['contact_lists']['contact_list']) ? $array['contact_lists']['contact_list'] : ''; if ($contact_lists_found !== '' ) { if (array_key_exists('0', $contact_lists_found)) { // more than contact list $contact_lists = $array['contact_lists']['contact_list']; } else { // only one contact list $contact_lists[0] = $array['contact_lists']['contact_list']; } } else { $contact_lists = array(); }
Advertisement
Answer
You could just check, if the key 0
is set, and if not, then simply overwrite the element contact_list
with itself wrapped into an array:
if(!isset($array['message']['contact_lists']['contact_list'][0])) { $array['message']['contact_lists']['contact_list'] = [ $array['message']['contact_lists']['contact_list'] ]; }
0
is not a valid tag name in XML, so you should never get that, unless there was more than one <contact_list>
in the XML.