PHP XML generation, chain `appendChild()`



我正在通过PHP生成一个XML文件,我是这样做的:

$dom  = new DOMDocument();
$root = $dom->createElement('Root');
...
// some node definitions here etc
$root->appendChild($product);
$root->appendChild($quantity);
$root->appendChild($measureUnit);
$root->appendChild($lineNumber);
...
$dom->appendChild($root);
$dom->save( '/some/dir/some-name.xml');

这一切都很好,直到我遇到一些问题,当我到达需要附加的部分时,比如说N子节点。这意味着我也将调用函数appendChild()'N'次,这导致了一个非常长的php脚本,有点难以维护。

我知道我们可以将主脚本拆分到更小的文件上以进行更好的维护,但有没有更好的方法来"连锁"appendChildren"调用,这样它就可以节省大量的书面行,或者有没有像"appendChildren"这样的神奇函数可用?

这是我第一次使用DOMDocument()类,我希望有人能给我一些启发。

谢谢

您可以将DOMDocument::createElement()嵌套到DOMNode::appendChild()调用中,并链接子节点或文本内容分配。

由于PHP 8.0DOMNode::append()可以用于附加多个节点和字符串。

$document = new DOMDocument();
// nest createElement inside appendChild
$document->appendChild(
// store node in variable
$root = $document->createElement('root')
);
// chain textContent assignment to appendChild
$root
->appendChild($document->createElement('product'))
->textContent = 'Example';

// use append to add multiple nodes  
$root->append(
$product = $document->createElement('measureUnit'),
$quantity = $document->createElement('quantity'),  
);
$product->textContent = 'cm';
$quantity->textContent = '42';

$document->formatOutput= true;
echo $document->saveXML();

输出:

<?xml version="1.0"?>
<root>
<product>Example</product>
<measureUnit>cm</measureUnit>
<quantity>42</quantity>
</root>

我正在使用可重复使用和可维护部件的接口,通常是:

interface XMLAppendable {

public function appendTo(DOMElement $parent): void;

}
class YourXMLPart implements XMLAppendable {

private $_product;
private $_unit;
private $_quantity;

public function __construct(string $product, string $unit, int $quantity) {
$this->_product = $product;
$this->_unit = $unit;
$this->_quantity = $quantity;
}

public function appendTo(DOMElement $parent): void {
$document = $parent->ownerDocument; 
$parent
->appendChild($document->createElement('product'))
->textContent = $this->_product;
$parent
->appendChild($document->createElement('measureUnit'))
->textContent = $this->_unit;
$parent
->appendChild($document->createElement('quantity'))
->textContent = $this->_quantity;
}
}

$document = new DOMDocument();
// nest createElement inside appendChild
$document->appendChild(
// store node in variable
$root = $document->createElement('root')
);
$part = new YourXMLPart('Example', 'cm', 42);
$part->appendTo($root);
$document->formatOutput= true;
echo $document->saveXML();

最新更新