【问题标题】:How to add an attribute to an XML Element in PHP without the xml header?如何在没有 xml 标头的 PHP 中向 XML 元素添加属性?
【发布时间】:2017-05-07 05:17:16
【问题描述】:

我需要为存储在 DB 中的 xml 元素添加一个新属性。这不是一个完整的 XML,而只是 DB 中的 XML 元素。

当我执行以下操作时,

$node_xml = simplexml_load_string('<node name="nodeA">this is a node</node>');
$node_xml->addAttribute('newattrib', "attribA");
$res_xml = $node_xml->asXML();

我得到$res_xml 为:

"<?xml version=\"1.0\"?>\n<node name=\"nodeA\" newattrib=\"attribA\">this is a node</node>\n"

如何在不进行字符串操作的情况下消除 &lt;?xml version=\"1.0\"?&gt; 部分?

【问题讨论】:

标签: php xml simplexml domdocument


【解决方案1】:

添加根级别,然后获取节点但不是完整的 xml。在这种情况下,标题将不会被回显

$string = '<node name="nodeA">this is a node</node>';
$node_xml = simplexml_load_string('<root>'. $string .'</root>');
$node = $node_xml->children()[0];
$node->addAttribute('newattrib', "attribA");

echo $res_xml = $node->asXML(); // <node name="nodeA" newattrib="attribA">this is a node</node>

demo

【讨论】:

    【解决方案2】:

    这里我们使用DOMDocument 在标签中设置属性。

    <?php
    
    ini_set('display_errors', 1);
    libxml_use_internal_errors(true);
    $domObject = new DOMDocument();
    $domObject->loadHTML('<node name="nodeA">this is a node</node>',LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
    $result=$domObject->getElementsByTagName("node")->item(0);
    $result->setAttribute("newattrib","attribA");
    echo $result->ownerDocument->saveHTML();
    

    输出: <node name="nodeA" newattrib="attribA">this is a node</node>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多