DOMDocument::createElementNS

(PHP 5, PHP 7, PHP 8)

DOMDocument::createElementNS โ€” ้–ข้€ฃไป˜ใ‘ใ‚‰ใ‚ŒใŸๅๅ‰็ฉบ้–“ใซๆ–ฐใ—ใ„่ฆ็ด ใ‚’ไฝœๆˆใ™ใ‚‹

่ชฌๆ˜Ž

public function DOMDocument::createElementNS(?string $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

ๅ‚่€ƒ

๏ผ‹add a note

User Contributed Notes 1 note

up
2
Martin ยถ
14 years ago
To avoid multiple xmlns re-declaration, make sure you appending ElementNS into actual DOMDocument tree (not into some currently-assembed derelict element).