xml insertion at specific point of xml file

て烟熏妆下的殇ゞ 提交于 2020-01-13 04:41:05

问题


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

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

immediately after:

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

in my xml file.

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

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

Thanks


回答1:


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

Output:

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

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



来源:https://stackoverflow.com/questions/7325960/xml-insertion-at-specific-point-of-xml-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!