XML语法属性PHP - 密钥问题

时间:2016-02-17 22:48:52

标签: php xml simplexml

我使用PHP创建XML文件

$xml=new SimpleXMLElement('<config/>');
$xml->addAttribute("xmlns","http://www.toto.com/tot_config_20110606");
$xml->addAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");
$xml->addAttribute("xsi:schemaLocation","http://www.toto.com/tot_config_20110606 config.xsd"); 

   //some childrens...

file_put_contents($filename, $xml->asXML() , LOCK_EX);

结果是一个正确的XML文件,但我的属性有问题

结果是:

<config xmlns="http://www.toto.com/tot_config_20110606" xsi="http://www.w3.org/2001/XMLSchema-instance" schemaLocation="http://www.toto.com/tot_config_20110606 config.xsd">
   //...
</config>

有人可以解释我如何保留整个密钥吗?

但我需要这个结果的第一部分:

<config  xmlns="http://www.toto.com/tot_config_20110606" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.toto.com/tot_config_20110606 config.xsd">
   //...
</config>

1 个答案:

答案 0 :(得分:1)

尝试一个 p.servus 制作here的建议,并将父模式的网址添加为addAttribute()的第三个参数:

$xml = new SimpleXMLElement("<config></config>");
$xml->addAttribute("xmlns","http://www.toto.com/tot_config_20110606");
/***** Update: the following line must be deleted****/
// $xml->addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance", "http://www.toto.com/tot_config_20110606"); 
$xml->addAttribute("xsi:schemaLocation", "http://www.toto.com/tot_config_20110606 config.xsd", "http://www.w3.org/2001/XMLSchema-instance"); 
echo $xml->asXml();