[英]How to create this XML using PHP SimpleXMLElement?
<?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>
我试过了
$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
前缀缺失
我试图在本地运行您的代码,但该代码无法执行。
我收到以下错误警告:
警告:SimpleXMLElement :: __ construct()[simplexmlelement .-- construct]:名称空间错误:在第3行的C:\\ wamp \\ www \\ test.php中无法解析QName'xmlns:x:'
因此,我有一个懒惰的建议(因为您生成的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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.