【问题标题】:xml insertion at specific point of xml file在 xml 文件的特定点插入 xml
【发布时间】:2011-09-07 05:13:02
【问题描述】:

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

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

紧接着:

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

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

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

谢谢

【问题讨论】:

    标签: php domdocument


    【解决方案1】:

    您要插入的行称为processing instruction。您可以像这样使用 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();
    

    输出:

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

    顺便说一句,使用str_replace 可能感觉不对,但如果它有效……它有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 2020-10-17
      • 2013-02-22
      • 1970-01-01
      相关资源
      最近更新 更多