使用SimpleXML创建XML时省略名称空间前缀

时间:2015-01-28 16:36:12

标签: php simplexml

我有以下代码

$base = '<?xml version="1.0" encoding="UTF-8"?><realestates:office xmlns:realestates="http://rest.immobilienscout24.de/schema/offer/realestates/1.0" xmlns:xlink="http://www.w3.org/1999/xlink"></realestates:office>';

$objXml = new \SimpleXMLElement($base);
$objXml->addChild('title', 'Alles Toller');
$strXml = $objXml->asXML();

$strXml现在

<?xml version="1.0" encoding="UTF-8"?>
<realestates:office xmlns:realestates="http://rest.immobilienscout24.de/schema/offer/realestates/1.0" xmlns:xlink="http://www.w3.org/1999/xlink">    
<realestates:title>Alles Toller</realestates:title>
</realestates:office>

我想要的是realestates:

中没有<title>前缀
<?xml version="1.0" encoding="UTF-8"?>
<realestates:office xmlns:realestates="http://rest.immobilienscout24.de/schema/offer/realestates/1.0" xmlns:xlink="http://www.w3.org/1999/xlink">    
<title>Alles Toller</title>
</realestates:office>

我该如何实现?

1 个答案:

答案 0 :(得分:0)

我最终使用DOMDocument

 $objXml = new \DOMDocument( "1.0", "UTF-8" );
 $objRoot = $objXml->createElement('realestates:office');
 $objXml->appendChild($objRoot);
 $objXml->createAttributeNS('http://rest.immobilienscout24.de/schema/offer/realestates/1.0', 'realestates:office');
 $objXml->createAttributeNS('http://www.w3.org/1999/xlink', 'xlink:dummy');
 $objTitle = $objXml->createElement('title', 'Alles Toll');
 $objRoot->appendChild($objTitle);
 $strXml = $objXml->saveXML();

createAttributeNS()的第二个参数有点奇怪 - 只有命名空间不够,看起来我还要添加一个元素名称。