©
本文档使用
php中文网手册 发布
(PHP 5 >= 5.2.0, PHP 7)
DOMDocument::registerNodeClass — Register extended class used to create base node type
$baseclass
, string $extendedclass
)This method allows you to register your own extended DOM class to be used afterward by the PHP DOM extension.
This method is not part of the DOM standard.
baseclass The DOM class that you want to extend. You can find a list of these classes in the chapter introduction.
extendedclass
Your extended class name. If NULL is provided, any previously
registered class extending baseclass will
be removed.
成功时返回 TRUE , 或者在失败时返回 FALSE 。
| 版本 | 说明 |
|---|---|
| 5.2.2 |
Prior to 5.2.2, a previously registered extendedclass
had to be unregistered before being able to register a new class extending
the same baseclass.
|
Example #1 Adding a new method to DOMElement to ease our code
<?php
class myElement extends DOMElement {
function appendElement ( $name ) {
return $this -> appendChild (new myElement ( $name ));
}
}
class myDocument extends DOMDocument {
function setRoot ( $name ) {
return $this -> appendChild (new myElement ( $name ));
}
}
$doc = new myDocument ();
$doc -> registerNodeClass ( 'DOMElement' , 'myElement' );
// From now on, adding an element to another costs only one method call !
$root = $doc -> setRoot ( 'root' );
$child = $root -> appendElement ( 'child' );
$child -> setAttribute ( 'foo' , 'bar' );
echo $doc -> saveXML ();
?> 以上例程会输出:
<?xml version="1.0"?> <root><child foo="bar"/></root>
Example #2 Retrieving elements as custom class
<?php
class myElement extends DOMElement {
public function __toString () {
return $this -> nodeValue ;
}
}
$doc = new DOMDocument ;
$doc -> loadXML ( "<root><element><child>text in child</child></element></root>" );
$doc -> registerNodeClass ( "DOMElement" , "myElement" );
$element = $doc -> getElementsByTagName ( "child" )-> item ( 0 );
var_dump ( get_class ( $element ));
// And take advantage of the __toString method..
echo $element ;
?> 以上例程会输出:
string(9) "myElement" text in child
Example #3 Retrieving owner document
When instantiating a custom DOMDocument the ownerDocument property will refer to the instantiated class, meaning there is no need (and in fact not possible) to use DOMDocument::registerNodeClass() with DOMDocument
<?php
class myDOMDocument extends DOMDocument {
}
class myOtherDOMDocument extends DOMDocument {
}
// Create myDOMDocument with some XML
$doc = new myDOMDocument ;
$doc -> loadXML ( "<root><element><child>text in child</child></element></root>" );
$child = $doc -> getElementsByTagName ( "child" )-> item ( 0 );
// The current owner of the node is myDOMDocument
var_dump ( get_class ( $child -> ownerDocument ));
// Import a node from myDOMDocument
$newdoc = new myOtherDOMDocument ;
$child = $newdoc -> importNode ( $child );
// The new owner of the node has changed to myOtherDOMDocument
var_dump ( get_class ( $child -> ownerDocument ));
?> 以上例程会输出:
string(13) "myDOMDocument" string(18) "myOtherDOMDocument"
[#1] crh3675 at gmail dot com [2009-09-25 20:23:46]
Creating innerHTML and outerHTML
<?php
class DOMHTMLElement extends DOMElement
{
function __construct() { parent::__construct();}
public function innerHTML()
{
$doc = new DOMDocument();
foreach ($this->childNodes as $child){
$doc->appendChild($doc->importNode($child, true));
}
$content = $doc->saveHTML();
return $content;
}
public function outerHTML()
{
$doc = new DOMDocument();
$doc->appendChild($doc->importNode($this, true));
$content = $doc->saveHTML();
return $content;
}
}
$dom = DOMDocument::loadHTMLFile($file);
$dom->registerNodeClass('DOMElement','DOMHTMLElement');
if($dom)
{
$xpath = new DOMXpath($dom);
$regions = $xpath->query("/
if($fragment->appendXML("<script type='text/javascript' src='$source'></script>") {
$xpath = new DOMXpath($doc);
$resultlist = $xpath->query("/
foreach($resultlist as $headnode) // insert the script tag
$headnode->appendChild($fragment);
}
$doc->saveXML();
?>
[#7] Bart Feenstra [2009-01-18 10:17:23]
I am using this solution to prevent tags and the doctype from being added to the HTML string automatically:
<?php
$html = '<h1>Hello world!</h1>';
$html = '<div>' . $html . '</div>';
$doc = new DOMDocument;
$doc->loadHTML($html);
echo substr($doc->saveXML($doc->getElementsByTagName('div')->item(0)), 5, -6)
// Outputs: "<h1>Hello world!</h1>"
?>
[#8] m at hbblogs daught calm [2008-08-18 08:41:41]
This method, as of 5.2.6, will automatically add <html><body> and <!DOCTYPE> tags to the document if they are missing, without asking whether you want them. In my application, I needed to use the DOM methods to manipulate just a fragment of html, so these tags were rather unhelpful.
Here's a simple hack to remove them in case, like me, all you wanted to do was perform a few operations on an HTML fragment.
$html_fragment = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
[#9] Anonymous [2008-04-25 20:15:25]
<?php
function getDOMString($retNode) {
if (!$retNode) return null;
$retval = strtr($retNode-->ownerDocument->saveXML($retNode),
array(
'></area>' => ' />',
'></base>' => ' />',
'></basefont>' => ' />',
'></br>' => ' />',
'></col>' => ' />',
'></frame>' => ' />',
'></hr>' => ' />',
'></img>' => ' />',
'></input>' => ' />',
'></isindex>' => ' />',
'></link>' => ' />',
'></meta>' => ' />',
'></param>' => ' />',
'default:' => '',
// sometimes, you have to decode entities too...
'"' => '"',
'&' => '&',
''' => ''',
'<' => '<',
'>' => '>',
' ' => ' ',
'©' => '©',
'«' => '«',
'®' => '®',
'»' => '»',
'™' => '™'
));
return $retval;
}
?>
[#10] mjaque at ilkebenson dot com [2008-02-19 11:34:37]
DOMDocument->saveXML() doesn't generate a proper XHTML format either.
There is a problem with "script" empty elements. For example:
This will be the code generated by saveXML, with an empty script tag.
<html>
<head>
<script type="text/JavaScript" src="myScript.js"/>
</head>
<body>
<p>I will not appear</p>
<script type="text/JavaScript">
alert("Not working");
</script>
</body>
</html>
I don't know if this is valid XHTML (W3C Validator doesn't complain), but both FF 2.0 and IE 6 will not render it properly. Both will use </script> as the closing tag for the first script causing js errors and ignoring in between elements.
You can post-process saveXML string in order to close empty tags with the following function:
<?php
function cerrarTag($tag, $xml){
$indice = 0;
while ($indice< strlen($xml)){
$pos = strpos($xml, "<$tag ", $indice);
if ($pos){
$posCierre = strpos($xml, ">", $pos);
if ($xml[$posCierre-1] == "/"){
$xml = substr_replace($xml, "></$tag>", $posCierre-1, 2);
}
$indice = $posCierre;
}
else break;
}
return $xml;
}
?>
At least script and select empty elements should be closed. This example shows how it can be used:
<?php
define("CABECERA_XHTML", '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
$xhtml = $docXML->saveXML($docXML->documentElement);
$xhtml = cerrarTag("script", $xhtml);
$xhtml = cerrarTag("select", $xhtml);
$xhtml = CABECERA_XHTML."\n".$xhtml;
echo $xhtml;
?>
[#11] archanglmr at yahoo dot com [2007-11-27 15:28:44]
If created your DOMDocument object using loadHTML() (where the source is from another site) and want to pass your changes back to the browser you should make sure the HTTP Content-Type header matches your meta content-type tags value because modern browsers seem to ignore the meta tag and trust just the HTTP header. For example if you're reading an ISO-8859-1 document and your web server is claiming UTF-8 you need to correct it using the header() function.
<?php
header('Content-Type: text/html; charset=iso-8859-1');
?>
[#12] xoplqox [2007-11-20 11:07:44]
XHTML:
If the output is XHTML use the function saveXML().
Output example for saveHTML:
<select name="pet" size="3" multiple>
<option selected>mouse</option>
<option>bird</option>
<option>cat</option>
</select>
XHTML conform output using saveXML:
<select name="pet" size="3" multiple="multiple">
<option selected="selected">mouse</option>
<option>bird</option>
<option>cat</option>
</select>
[#13] tyson at clugg dot net [2005-04-21 17:44:56]
<?php
// Using DOM to fix sloppy HTML.
// An example by Tyson Clugg <tyson@clugg.net>
//
// vim: syntax=php expandtab tabstop=2
function tidyHTML($buffer)
{
// load our document into a DOM object
$dom = @DOMDocument::loadHTML($buffer);
// we want nice output
$dom->formatOutput = true;
return($dom->saveHTML());
}
// start output buffering, using our nice
// callback funtion to format the output.
ob_start("tidyHTML");
?>
<html>
<p>It's like comparing apples to oranges.
</html>
<?php
// this will be called implicitly, but we'll
// call it manually to illustrate the point.
ob_end_flush();
?>
The above code takes out sloppy HTML:
<html>
<p>It's like comparing apples to oranges.
</html>
And cleans it up to the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>It's like comparing apples to oranges.
</p></body></html>