2017-04-23 41 views
1

我用的SimpleXMLElement工作的第一次,需要生成我的XML如下一行:PHP的SimpleXMLElement的addAttribute命名空間語法

<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'); 

,但不能工作,如何解決此爲適當的語法來生成所需的輸出?

回答

0

解決方案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:將直接命名空間LY在的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"/>