SimpleXML insert Processing Instruction (Stylesheet)

跟風遠走 提交于 2019-12-01 13:36:23
hakre

A SimpleXMLElement does not allow you by default to create and add a Processing Instruction (PI) to a node. However the sister library DOMDocument allows this. You can marry the two by extending from SimpleXMLElement and create a function to provide that feature:

class MySimpleXMLElement extends SimpleXMLElement
{
    public function addProcessingInstruction($target, $data = NULL) {
        $node   = dom_import_simplexml($this);
        $pi     = $node->ownerDocument->createProcessingInstruction($target, $data);
        $result = $node->appendChild($pi);
        return $this;
    }
}

This then is easy to use:

$output = '<hotel/>';
$hotel  = simplexml_load_string($output, 'MySimpleXMLElement');
$hotel->addProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="style.xsl"');
$hotel->asXML('php://output');

Exemplary output (beautified):

<?xml version="1.0"?>
<hotel>
  <?xml-stylesheet type="text/xsl" href="style.xsl"?>
</hotel>

Another way is to insert an XML chunk to a simplexml element: "PHP SimpleXML: insert node at certain position" or "Insert XML into a SimpleXMLElement".

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