(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
.
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
peter-SPAMrubbish-ATveridon.com (2008-03-05 23:06:44)
Something that surprised me, any changes made to the SimpleXML object obtained from the imported DOMDocument also change the original DOMDocument.
e.g.
<?php
$string = '<root><foo>abc</foo></root>';
$domxml = DOMDocument::loadXML($string);
$simplexml = simplexml_import_dom($domxml);
$simplexml->foo = "xyz";
$simplexml->bar = "123";
echo $domxml->saveXML();
?>
Outputs:
--START--
<?xml version="1.0"?>
<root><foo>xyz</foo><bar>123</bar></root>
spam AT media MINUS soma DOT de (2006-07-26 09:27:09)
Please note that a valid SimpleXMLElement is typecasted to false.
<?php
$string = '<root><foo>abc</foo></root>';
$xml = DOMDocument::loadXML($string);
$xml = simplexml_import_dom($xml);
echo 'simplexml_import_dom';
var_dump($xml);
var_dump((bool)$xml);
$xml = simplexml_load_string('<root><foo>abc</foo></root>');
echo 'simplexml_load_string';
var_dump($xml);
var_dump((bool)$xml);
$xml = simplexml_load_file('test.xml');
echo 'simplexml_load_file';
var_dump($xml);
var_dump((bool)$xml);
?>
Outputs:
--START--
simplexml_import_dom
object(SimpleXMLElement)[2]
public 'foo' => 'abc'
false
simplexml_load_string
object(SimpleXMLElement)[1]
public 'foo' => 'abc'
false
simplexml_load_file
object(SimpleXMLElement)[2]
public 'foo' => 'abc'
false
--END--