【问题标题】:PHP: How to add attributes to the deeper child note with SimpleXMLElementPHP:如何使用 SimpleXMLElement 向更深的子注释添加属性
【发布时间】:2013-09-14 09:46:20
【问题描述】:

如何使用SimpleXMLElement 将属性添加到更深层的子笔记?例如,

$xml = new SimpleXMLElement('<xml/>');

$response = $xml->addChild('response');
$response->addChild('error');
$response->addAttribute('elementid', 100);
$response->addAttribute('message', 'You must not leave this field empty!');


Header('Content-type: text/xml');
print($xml->asXML());

我明白了,

<xml>
<response elementid="100" message="Key name - You must not leave this field empty!">
<error />
</response>
</xml>

但其实我想要,

<xml>
<response>
<error elementid="100" message="Key name - You must not leave this field empty!" />
</response>
</xml>

有可能吗?

【问题讨论】:

    标签: php xml simplexml php-5.4


    【解决方案1】:
    <?php
    $xml = new SimpleXMLElement('<xml/>');
    
    $response   = $xml->addChild('response');
    $error      = $response->addChild('error');
    $error->addAttribute('elementid', 100);
    $error->addAttribute('message', 'You must not leave this field empty!');
    
    Header('Content-type: text/xml');
    print($xml->asXML());
    

    【讨论】:

    • 感谢您的帮助!
    • 是否清楚出了什么问题?我认为代码很清楚地指出了它是否出错了,对吧?
    • 是的,很清楚。现在我明白出了什么问题。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多