使用 PHP 中的 DOMDocument 将新属性编辑到 XML 元素

Editing new attribute to XML element using DOMDocument in PHP

目前我的 MVC 应用程序中有这个 XML 文档

<elements>   
   <element name="agents" path="admin/agents" scope="system">
       <folder function="model">models</folder>
       <folder function="controller">controllers</folder>
       <folder function="view">views</folder>
   </element> 
</elements>

我想使用 DOMDocument 向元素添加额外的 "visibility=hidden" 属性。如何做到这一点?

使用createAttribute(),例如:

$raw = <<<XML
<elements>   
   <element name="agents" path="admin/agents" scope="system">
       <folder function="model">models</folder>
       <folder function="controller">controllers</folder>
       <folder function="view">views</folder>
   </element> 
</elements>
XML;
$doc = new DOMDocument();
$doc->loadXML($raw);

$visibility = $doc->createAttribute('visiblity');
$visibility->value = 'hidden';

$element = $doc->getElementsByTagName('element')->item(0);
$element->appendChild($visibility);
echo $doc->saveXML();

eval.in demo

输出:

<?xml version="1.0"?>
<elements>   
   <element name="agents" path="admin/agents" scope="system" visiblity="hidden">
       <folder function="model">models</folder>
       <folder function="controller">controllers</folder>
       <folder function="view">views</folder>
   </element> 
</elements>

大多数人为此使用 DOMElement::setAttribute()DOMElement::setAttributeNS() 方法。

$xml = <<<XML
<elements>   
   <element name="agents" path="admin/agents" scope="system"> 
     ...
   </element> 
</elements>
XML;

$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);

foreach ($xpath->evaluate('//element[1]') as $element) {
  $element->setAttribute('visibility', 'hidden');
}
echo $document->saveXML();

输出:

<?xml version="1.0"?>
<elements>   
   <element name="agents" path="admin/agents" scope="system" visibility="hidden"> 
     ...
   </element> 
</elements>

然而属性也是节点。因此,您可以使用 DOMDocument::createAttribute() 创建它们并使用 DOMElement::setAttributeNode() 进行设置。这允许将创建与分配分开。

foreach ($xpath->evaluate('//element[1]') as $element) {
  $attribute = $document->createAttribute('visibility');
  $attribute->value = 'hidden';
  $element->setAttributeNode($attribute);
}