SimpleXML insert Processing Instruction (Stylesheet)

前端 未结 1 466
北荒
北荒 2021-01-16 13:19

I want to integrate an XSL file in an XML string gived me by php CURL command. I tryed this

$output = XML         


        
相关标签:
1条回答
  • 2021-01-16 14:01

    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".

    0 讨论(0)
提交回复
热议问题