在xml文件的特定点插入xml [英] xml insertion at specific point of xml file

查看:77
本文介绍了在xml文件的特定点插入xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to insert the following line into my xml file:

<?xml-stylesheet type="text/xsl" href="http://example.com/livesearch.xsl"?>

紧接在以下位置:

<?xml version="1.0" encoding="UTF-8" ?>

在我的xml文件中。

当前我使用这种(糟糕的)方法:

Currently I use this (awful) method:

$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']);

在php中使用DomDocument的正确方法是什么?

What is the correct way to do this with DomDocument in php?

谢谢

推荐答案

您要插入的行称为处理指令。您可以使用DOM这样添加它:

The line you want to insert is called a processing instruction. You can add it with DOM like this:

$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();

输出:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="http://example.com/livesearch.xsl"?>
<root/>

在旁注中,使用 str_replace ,但如果可以…就可以。

On a sidenote, it might feel wrong to use str_replace but if it works … it works.

这篇关于在xml文件的特定点插入xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆