Skip to content
Advertisement

XML parsing is not working when it’s only one array

I am parsing the xml like following:

JavaScript

A sometimes the array look like this, which is works.

JavaScript

B but sometime if the array has only one contact_list, it will look like following

JavaScript

when i use $contact_listsin 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:

JavaScript

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement