©
Dokumen ini menggunakan Manual laman web PHP Cina Lepaskan
(PHP 5)
simplexml_import_dom — Get a SimpleXMLElement object from a DOM node.
$node
[, string $class_name
= "SimpleXMLElement"
] )This function takes a node of a DOM document and makes it into a SimpleXML node. This new object can then be used as a native SimpleXML element.
node
A DOM Element node
class_name
You may use this optional parameter so that simplexml_import_dom() will return an object of the specified class. That class should extend the SimpleXMLElement class.
Returns a SimpleXMLElement 或者在失败时返回 FALSE
.
此函数可能返回布尔值
FALSE
,但也可能返回等同于 FALSE
的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用
===
运算符来测试此函数的返回值。
Example #1 Importing DOM
<?php
$dom = new DOMDocument ;
$dom -> loadXML ( '<books><book><title>blah</title></book></books>' );
if (! $dom ) {
echo 'Error while parsing the document' ;
exit;
}
$s = simplexml_import_dom ( $dom );
echo $s -> book [ 0 ]-> title ;
?>
以上例程会输出:
blah
[#1] brandonkirsch at perceptionilluminates dot com [2013-08-14 15:38:27]
simplexml_import_dom() will accept DOMNodes or other SimpleXMLElements. This has a useful purpose if you are extending the SimpleXMLElement class and would prefer the xpath() method to return your class extension instead of basic SimpleXMLElements. For example:
class MySimpleXML extends SimpleXMLElement{
public function xpath($xpath){
$return = array();
$simpleXmls = parent::xpath($xpath); // run SimpleXMLElement xpath, returning an array of SimpleXMLElements
foreach($simpleXmls as $xml){
$return[] = simplexml_import_dom($xml,'MySimpleXML'); // copy SimpleXMLElement, returning as MySimpleXML instance
}
return $return;
}
}
Now I can create an instance of MySimpleXML, run an xpath, and get my results back as an array of MySimpleXML elements instead of the native SimpleXMLElement:
$mySimpleXml = new mySimpleXml('<root><node/></root>');
$array = $mySimpleXml->xpath('/root/node'); // returns array with a single MySimpleXml object