如何进入 PHP 中 XML 文件的 child 而不是 'firstChild'?

How to get into into another child than 'firstChild' of XML file in PHP?

除了 PHP 中的 firstChild,我如何才能通过另一个 child of XML 文件? 我有这样的代码:

        $root = $xmldoc->firstChild;

我可以直接进入第二名 child 或其他吗?

您的问题的可能解决方案可能是这样的。首先是您的 XML 结构。你问的是如何将项目节点添加到数据节点。

$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<xmldata>
    <data>
        <item>item 1</item>
        <item>item 2</item>
    </data>
</xmldata>
XML;

在 PHP 中,一种可能的解决方案是 DomDocument 对象。

$doc = new \DomDocument();
$doc->loadXml($xml);

// fetch data node
$dataNode = $doc->getElementsByTagName('data')->item(0);

// create new item node
$newItemNode = $doc->createElement('item', 'item 3');

// append new item node to data node
$dataNode->appendChild($newItemNode);

// save xml node
$doc->saveXML();

此代码示例未经测试。玩得开心。 ;)