SimpleXML insert Processing Instruction (Styleshee

2019-03-03 06:04发布

问题:

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

$output = XML gived me by curl option;
$hotel = simplexml_load_string($output);
$hotel->addAttribute('?xml-stylesheet type=”text/xsl” href=”css/stile.xsl”?');
echo $hotel->asXML();

Doing this when I see the XML on browser, I receive the file without the stylesheet. Where is my error?

回答1:

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