To avoid multiple xmlns re-declaration, make sure you appending ElementNS into actual DOMDocument tree (not into some currently-assembed derelict element).(PHP 5, PHP 7, PHP 8)
DOMDocument::createElementNS โ ้ข้ฃไปใใใใๅๅ็ฉบ้ใซๆฐใใ่ฆ็ด ใไฝๆใใ
$namespace, string $qualifiedName, string $value = ""): DOMElement|falseใใฎ้ขๆฐใฏใ้ข้ฃไปใใใใๅๅ็ฉบ้ใซๆฐใใ่ฆ็ด ใไฝๆใใพใใ ใใฎใใผใใฏใ( DOMNode::appendChild() ใชใฉใง) ๆฟๅ ฅใใใชใ้ใใใใญใฅใกใณใๅ ใซใใใใใพใใใ
namespaceๅๅ็ฉบ้ใฎ URIใ
qualifiedName
่ฆ็ด ๅใใprefix:tagname
ใฎใใใชๅฝขๅผใงๆๅฎใใใ
value่ฆ็ด ใฎๅคใใใใฉใซใใงใฏใ็ฉบใฎ่ฆ็ด ใไฝๆใใใพใใ ใใฎๅพใซ DOMElement::$nodeValue ใงๅคใ่จญๅฎใใใใจใๅฏ่ฝใงใใ
ๆฐใใ DOMElementใ
ใใใใฏใจใฉใผใ็บ็ใใๅ ดๅใซใฏ false ใ่ฟใใพใใ
ไปฅไธใฎใจใฉใผใณใผใใง DOMException ใในใญใผใใพใ:
DOM_INVALID_CHARACTER_ERR
qualifiedName ใ็กๅนใชๆๅญใๅซใใงใใๅ ดๅใซ็บ็ใใพใใ
DOM_NAMESPACE_ERR
qualifiedName ใ็กๅนใชๅๅใงใใๅ ดๅใซ็บ็ใใพใใ
ไพ1 ๆฐใใ่ฆ็ด ใไฝๆใใใซใผใใจใใฆๆฟๅ ฅใใ
<?php
$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');
// ๆฐใใ่ฆ็ด ใใซใผใ (ใใญใฅใกใณใใฎๅญ่ฆ็ด ) ใจใใฆๆฟๅ
ฅใใ
$dom->appendChild($element);
echo $dom->saveXML();
?>ไธใฎไพใฎๅบๅใฏไปฅไธใจใชใใพใใ
<?xml version="1.0" encoding="iso-8859-1"?> <xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>
ไพ2 ๅๅ็ฉบ้ใใฌใใฃใใฏในใฎไพ
<?php
$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElementNS('http://www.w3.org/2005/Atom', 'element');
$doc->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:g', 'http://base.google.com/ns/1.0');
$item = $doc->createElementNS('http://base.google.com/ns/1.0', 'g:item_type', 'house');
$root->appendChild($item);
echo $doc->saveXML(), "\n";
echo $item->namespaceURI, "\n"; // ๅบๅ: http://base.google.com/ns/1.0
echo $item->prefix, "\n"; // ๅบๅ: g
echo $item->localName, "\n"; // ๅบๅ: item_type
?>ไธใฎไพใฎๅบๅใฏไปฅไธใจใชใใพใใ
<?xml version="1.0" encoding="utf-8"?> <element xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0"> <g:item_type>house</g:item_type> </element> http://base.google.com/ns/1.0 g item_type