2014-04-28 38 views
0
<?xml version="1.0" encoding="UTF-8"?> 
<x:NetworkRequest xmlns:x="http://www.google.com" xmlns:xsi="http://www.w3.org"> 
    <Version>2.0.0</Version> 
    <IpAddress>127.0.0.1</IpAddress> 
</x:NetworkRequest> 

我試圖如何使用PHP SimpleXMLElement創建此XML?

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?><xmlns:x:NetworkRequest></xmlns:x:NetworkRequest>'); 
$xml->addAttribute('xmlns:x','http://www.google.com'); 
$xml->addAttribute('xmlns:xsi','http://www.w3.org'); 
$xml->addChild('Version','2.0.0'); 
$xml->addChild('IpAddress','127.0.0.1'); 
echo $xml->asXML(); 

,並得到:

<?xml version="1.0" encoding="UTF-8"?> 
<x:NetworkRequest x="http://www.google.com" xsi="http://www.w3.org"> 
    <Version>2.0.0</Version> 
    <IpAddress>127.0.0.1</IpAddress> 
</x:NetworkRequest> 

xmlns:前綴缺少x="http://www.google.com"xsi="http://www.w3.org

回答

0

我試圖在本地運行代碼,也不會執行。

我得到了下面錯誤警告:

警告:的SimpleXMLElement :: __結構()的SimpleXMLElement .--構建]: 命名空間錯誤:無法解析的QName '的xmlns:X:' 在 C:\ WAMP \ WWW \ test.php的上線3

所以,我這個懶人的建議(看到,因爲你是生產的XML不是複雜或需要修改的飛行,我回避的SimpleXMLElement類一樣這樣):

<?php 

function getNetworkRequestXML($version, $ip_address) { 
    return '<?xml version="1.0" encoding="UTF-8"?> 
<x:NetworkRequest xmlns:x="http://www.google.com" xmlns:xsi="http://www.w3.org"> 
    <Version>'. $version .'</Version> 
    <IpAddress>'. $ip_address .'</IpAddress> 
</x:NetworkRequest>'; 
} 

var_dump(getNetworkRequestXML('2.0.0', '127.0.0.1')); 

?> 

輸出:

<?xml version="1.0" encoding="UTF-8"?> 
<x:NetworkRequest xmlns:x="http://www.google.com" xmlns:xsi="http://www.w3.org"> 
    <Version>2.0.0</Version> 
    <IpAddress>127.0.0.1</IpAddress> 
</x:NetworkRequest> 
+0

那些警告,而不是錯誤。 – ohho