Skip to content
Advertisement

How to fix simpleXML “Warning: Illegal string offset” for node name?

I work with simpleXML to parse some XML responses from server, which I load like this:

$xml = simplexml_load_string($string);

It has a one and only one child, but with different names for different responses, so I get child name first:

$node = $xml->children()->getName();

I make new object Response and set his properties to what I read from that XML string:

return (new Response())
    ->setTime((string)$xml['time'])
    ->setId((string)$xml->$node['id'])
    ->setResult((string)$xml->$node['result'])
    ->setBalance((string)$xml->$node->balance['value']);

And here this warning comes – Illegal string offset 'id', Illegal string offset 'result'

I know, that $node is actually a string, but it used as name of the node in response. If I change my code to ->setId((string)$xml->result['id']), the warning disappear. The problem, that I do not know the name of the node, before response actually comes (for example it can be “good_result”, “result_1” and so on). So, the ‘$node[‘id’]’ is not ask for string index, but for attribute of node. It looks like collision between PHP string index syntax and simpleXML node name syntax.

  1. The code itself work just fine, warning comes only in IDE
  2. There are a lot of similar questions about simpleXML, but no answer to my case
  3. I need just to remove that warning, so answer how to fix it in code, or remove such warnings are accepted

Advertisement

Answer

There are two possible ways to interpret code of this form:

$object->$foo['bar'];
  • Versions of PHP since 7.0 will look up the property identified by $foo, and then look up the key 'bar' on the result, which is what you want.
  • Older versions of PHP would evaluate $foo['bar'] first, and then look up the property based on that result.

The warning in your IDE is assuming the old interpretation: it’s warning you that $foo['bar'] doesn’t make sense, because $foo is a string.

Unless you’re actually running your code in an ancient version of PHP (5.6 hasn’t had an official security update for over 2 years), there is no actual problem with the code. You need to either upgrade your IDE, or re-configure it, so that it interprets code the same way the actual PHP will. Since you don’t mention what IDE you’re using, I can’t be more specific.

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