PHP SimpleXMLElement addAttribute命名空间语法

时间:2017-04-23 00:00:47

标签: php namespaces simplexml

我是第一次使用SimpleXMLElement,需要在我的XML中生成一行,如下所示:

<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

我之前没有使用addAttribute和命名空间,并且无法在此处使用正确的语法 - 我已经开始使用它了:

$node = new SimpleXMLElement('< Product ></Product >');
$node->addAttribute("xmlns:", "xsd:", 'http://www.w3.org/2001/XMLSchema-instance'); 

但是不能弄清楚如何纠正这个以获得适当的语法来生成所需的输出?

1 个答案:

答案 0 :(得分:1)

解决方案1:为前缀添加前缀

<?php
$node = new SimpleXMLElement('<Product/>');
$node->addAttribute("xmlns:xmlns:xsi", 'http://www.w3.org/2001/XMLSchema-instance');
$node->addAttribute("xmlns:xmlns:xsd", 'http://www.w3.org/2001/XMLSchema');
echo $node->asXML();

输出:

<?xml version="1.0"?>
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>

注意:这是一种解决方法,实际上并没有设置属性的命名空间,但是如果你要回显/保存以提交结果,那就足够了

解决方案2:将命名空间直接放在SimpleXMLElement构造函数

<?php
$node = new SimpleXMLElement('<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>');
echo $node->asXML();

输出与解决方案1相同

解决方案3(添加其他属性)

<?php
$node = new SimpleXMLElement('<Product/>');
$node->addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance", "xmlns");
$node->addAttribute("xmlns:xsd", 'http://www.w3.org/2001/XMLSchema', "xmlns");
echo $node->asXML();

输出会添加额外的xmlns:xmlns="xmlns"

<?xml version="1.0"?>
<Product xmlns:xmlns="xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>
相关问题