开发者

Force SimpleXML node to always be an array, even if just 1 element in it

Let's say I want a Place to have a list of phone numbers. Some places will have 1 phone number, and some will have more than one. Others won't have on开发者_JAVA百科e at all.

The problem is that this:

$xml->addChild('phone_number','555.555.5555');

creates a non-iterable phone_number text node:

$response->xml->phone_number;

But this:

$xml->addChild('phone_number','555.555.5555');
$xml->addChild('phone_number','555.555.5556');

creates an iterable array of phone_number:

$response->xml->phone_number[0];
$response->xml->phone_number[1];

This puts an unnecessary burden on the client. They have to detect if the result is iterable or not, and modify their code accordingly.

It would be MUCH better if I could always send back an interable array, even if it had 0 or 1 items in it... but I haven't been able to find any documentation on how to do this. In Perl I believe it's called "forcearray", but I haven't found an equivalent for PHP, which is waht i need.


Just don't use this fancy, magic interface ($obj->xml->phone_number[x]) and use SimpleXMLElement::children() method which always returns iterable object.


you should consider this

<phone_numbers>
  <phone_number>555.555.5555</phone_number>
</phone_numbers>

this is more flexible

beside the children() method, you can also consider xpath
which always will yields an array to be return

example

$xml = <<<XML
<person>
  <phone_numbers>
    <phone_number>555.555.5555</phone_number>
  </phone_numbers>
</person>
XML;

$obj  = simplexml_load_string($xml);
$tels = $obj->xpath("//phone_numbers/*");

/* even more simple */
$tels = $obj->phone_numbers->children();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜