note 95229 modified in class.simplexmlelement by danbrown
| From: | danbrown@php.net | Date: | Sun, 20 Dec 2009 03:44:19 +0000 |
| Subject: | note 95229 modified in class.simplexmlelement by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-164149@lists.php.net to get a copy of this message | ||
It's occasionally useful to add an XML processing instruction to a SimpleXMLElement (treating
it as if it were a full document).
<?php
class SimpleXMLElement_Plus extends SimpleXMLElement {
public function addProcessingInstruction( $name, $value )
{
// Create a DomElement from this simpleXML object
$dom_sxe = dom_import_simplexml($this);
// Create a handle to the owner doc of this xml
$dom_parent = $dom_sxe->ownerDocument;
// Find the topmost element of the domDocument
$xpath = new DOMXPath($dom_parent);
$first_element = $xpath->evaluate('/*[1]')->item(0);
// Add the processing instruction before the topmost element
$pi = $dom_parent->createProcessingInstruction($name, $value);
$dom_parent->insertBefore($pi, $first_element);
}
}
?>
For example, if you had a simpleXMLElement_Plus object made out of the xml fragment:
<xml><content /></xml>
And you needed the output to be:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="xsl/xsl.xsl"?>
<xml><content/></xml>
you could do (using the class above):
<?php
$xml = new SimpleXMLElement_Plus('<xml><content /></xml>');
$xml->addProcessingInstruction('xml-stylesheet', 'type="text/xsl"
href="xsl/xsl.xsl"');
echo $xml->asXML();
?>
--was--
It's occasionally useful to add an XML processing instruction to a SimpleXMLElement (treating
it as if it were a full document).
<?php
class SimpleXMLElement_Plus extends SimpleXMLElement {
public function addProcessingInstruction( $name, $value )
{
// Create a DomElement from this simpleXML object
$dom_sxe = dom_import_simplexml($this);
// Create a handle to the owner doc of this xml
$dom_parent = $dom_sxe->ownerDocument;
// Find the topmost element of the domDocument
$xpath = new DOMXPath($dom_parent);
$first_element = $xpath->evaluate('/*[1]')->item(0);
// Add the processing instruction before the topmost element
$pi = $dom_parent->createProcessingInstruction($name, $value);
$dom_parent->insertBefore($pi, $first_element);
}
}
?>
For example, if you had a simpleXMLElemnt_Plus object made out of the xml fragment:
<xml><content /></xml>
And you needed the output to be:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="xsl/xsl.xsl"?>
<xml><content/></xml>
you could do (using the class above):
$xml = new SimpleXMLElement_Plus('<xml><content /></xml>');
$xml->addProcessingInstruction('xml-stylesheet', 'type="text/xsl"
href="xsl/xsl.xsl"');
echo $xml->asXML();
http://php.net/manual/en/class.simplexmlelement.php