在PHP中指定请求中同名的子节点


Specify to children of same name in request in PHP

我需要建立一个类似于这样的请求:

<rooms>
<room>12345</room>
<room>65679</room>
</rooms>

然而,我插入一个房间像:

$request->therequest->rooms['room'] = 123456;

但是当我对第二个字符再次执行此操作时,它会覆盖第一个字符。我如何在"房间"下指定2个孩子的"房间"而不覆盖它们?

谢谢!

您应该考虑使用SimpleXMLElement。然后你只需这样做:

$templateXML = "<rooms></rooms>";
$xmlElement = new SimpleXMLElement($templateXML);
$xmlElement->addChild("room", 12345);
$xmlElement->addChild("room", 65679);
print $xmlElement->asXML();

输出将是:

<?xml version="1.0"?>
<rooms>
    <room>12345</room>
    <room>65679</room>
</rooms>

阅读更多关于SimpleXMLElement在这里。这里是关于addChild方法的更多信息

您需要创建一个房间数组。您可以像这样将它添加到数组中:

$request->therequest->rooms['room'][] = 123456;

$request->therequest->rooms['room'][0]呢?