在xml文件的特定点插入xml

kha*_*any 3 php domdocument

我想在我的xml文件中插入以下行:

<?xml-stylesheet type="text/xsl" href="http://example.com/livesearch.xsl"?>
Run Code Online (Sandbox Code Playgroud)

之后立马:

<?xml version="1.0" encoding="UTF-8" ?>
Run Code Online (Sandbox Code Playgroud)

在我的xml文件中.

目前我使用这个(糟糕的)方法:

$G['xml'] = str_replace('<?xml version="1.0" encoding="UTF-8" ?>', '<?xml version="1.0" encoding="UTF-8" ?><?xml-stylesheet type="text/xsl" href="http://example.com/livesearch.xsl"?>', $G['xml']);
Run Code Online (Sandbox Code Playgroud)

在php中使用DomDocument执行此操作的正确方法是什么?

谢谢

Gor*_*don 5

要插入的行称为处理指令.您可以像这样添加DOM:

$dom = new DOMDocument();
$dom->loadXml('<?xml version="1.0" encoding="UTF-8" ?><root/>');

$dom->insertBefore(
    $dom->createProcessingInstruction(
        'xml-stylesheet',
        'type="text/xsl" href="http://example.com/livesearch.xsl"'
    ),
    $dom->documentElement
);
echo $dom->saveXml();
Run Code Online (Sandbox Code Playgroud)

输出:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="http://example.com/livesearch.xsl"?>
<root/>
Run Code Online (Sandbox Code Playgroud)

在旁注中,使用它可能会有误,str_replace但如果它有效......它可以工作.