SimpleXMLElement::__construct
(PHP 5, PHP 7, PHP 8)
SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
说明
string
$data
,int
$options
= 0,bool
$dataIsURL
= false
,string
$namespaceOrPrefix
= "",bool
$isPrefix
= false
)
Creates a new SimpleXMLElement object.
参数
-
data
-
A well-formed XML string or the path or URL to an XML document if
dataIsURL
istrue
. -
options
-
Optionally used to specify additional Libxml parameters, which affect reading of XML documents. Options which affect the output of XML documents (e.g.
LIBXML_NOEMPTYTAG
) are silently ignored.注意:
It may be necessary to pass
LIBXML_PARSEHUGE
to be able to process deeply nested XML or very large text nodes. -
dataIsURL
-
By default,
dataIsURL
isfalse
. Usetrue
to specify thatdata
is a path or URL to an XML document instead of string data. -
namespaceOrPrefix
-
Namespace prefix or URI.
-
isPrefix
-
true
ifnamespaceOrPrefix
is a prefix,false
if it's a URI; defaults tofalse
.
错误/异常
Produces an E_WARNING
error message for each error
found in the XML data and additionally throws an Exception if the XML data
could not be parsed.
Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.
范例
注意:
Listed examples may include
example.php
, which refers to the XML string found in the first example of the basic usage guide.
示例 #1 Create a SimpleXMLElement object
<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;
?>
以上例程会输出:
PHP: Behind the Parser
示例 #2 Create a SimpleXMLElement object from a URL
<?php
$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe->asXML();
?>
参见
- Basic SimpleXML usage
- simplexml_load_string() - Interprets a string of XML into an object
- simplexml_load_file() - Interprets an XML file into an object
- Dealing with XML errors
- libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
- libxml_set_streams_context() - Set the streams context for the next libxml document load or write

User Contributed Notes 8 notes
The manual doesn't really explain what the $ns argument (and the accompanying $is_prefix) are for.
What they do is similar to the ->children() method: they set the context of the returned object to that namespace, so that access via ->elementName and ['attributeName'] refer to elements and attributes in that namespace.
In particular, they do *not* change the namespaces which exist on the document.
See this example:
<?php
// This XML contains two elements called <child>
// One is in the namespace http://example.com, with local prefix 'ws'
// The other has no namespace (no prefix, and no default namespace declared)
$xml = '<ws:example xmlns:ws="http://example.com"><child>Not in namespace</child><ws:child>In example namespace</ws:child></ws:example>';
$sx0 = new SimpleXMLElement($xml, 0, false);
$sx1 = new SimpleXMLElement($xml, 0, false, 'http://example.com');
$sx2 = new SimpleXMLElement($xml, 0, false, 'ws', true);
echo "
Without: {$sx0->child}
By namespace: {$sx1->child}
By prefix: {$sx2->child}
";
?>
Output:
Without: Not in namespace
By namespace: In example namespace
By prefix: In example namespace
Extended SimpleXMLElement:
<?php
class XmlElement extends \SimpleXMLElement
{
public static function factory(string $root): self
{
return new static('<?xml version="1.0" encoding="UTF-8"?><'.$root.'/>', LIBXML_BIGLINES | LIBXML_COMPACT);
}
/**
* @param iterable $attributes An array of element attributes as name/value pairs
* @return $this
*/
public function addAttributes(iterable $attributes)
{
foreach ($attributes as $name => $value) {
$this->addAttribute($name, $value);
}
return $this;
}
/**
* @param string $name The sub-element name
* @param string|array|null $valueOrAttributes The sub-element value or an array of attributes
* @param string|null $namespace The sub-element namespace
* @return static|null
*/
public function addChild($name, $valueOrAttributes = null, $namespace = null)
{
if (is_array($valueOrAttributes)) {
$child = parent::addChild($name, null, $namespace);
foreach ($valueOrAttributes as $name => $value) {
$child->addAttribute($name, $value);
}
} else {
$child = parent::addChild($name, $valueOrAttributes, $namespace);
}
return $child;
}
/**
* @param iterable $childs An array of sub-elements as name/value(or attributes) pairs
* @return $this
*/
public function addChilds(iterable $childs)
{
foreach ($childs as $name => $value) {
$this->addChild($name, $value);
}
return $this;
}
}
?>
This class is extendable, but it's too bad that its constructor cannot be overriden (PHP says it's a final method). Thus the class should be wrapped using the delegation principle rather that extended.
You won't be able to load an XML file without root element:
//This will throw an exception
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>', null, false);
//Here is the solution
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>', null, false);
It's worth noting that the behavior of SimpleXmlElement::__construct is not exactly the same as simplexml_load_string, regarding libxml_use_internal_errors().
In my case,
<?php
libxml_use_internal_errors(true);
new \SimpleXmlElement($data);
?>
was still throwing error. But as soon as I switched to
<?php
libxml_use_internal_errors(true);
simplexml_load_string($data);
?>
everything worked fine and I stopped getting an error.
Using libxml_use_internal_errors() may suppress errors but Exception still requires decent handling. I used following code snippet.
<?php
libxml_use_internal_errors(true);
try{
$xmlToObject = new SimpleXMLElement($notSoWellFormedXML);
} catch (Exception $e){
echo 'Please try again later...';
exit();
}
?>
As I was filling out a bug report, I realized why (speculation here) the constructor is final: so that functions like simplexml_load_file and simplexml_load_string can work. I imagine the PHP-ized code looks something like
<?php
function simplexml_load_file($filename, $class_name = "SimpleXMLElement", $options = 0, $ns = "", $is_prefix = false) {
return new $class_name($filename, $options, true, $ns, $is_prefix);
}
?>
If we were to use a different $class_name and change the constructor's definition these functions wouldn't work.
There's no easy, sensible solution that keeps simplexml_load_file and simplexml_load_string.
It's worth noting, that you need to typecast dynamic property names to string in order to retrieve there value, for example:
<?php
$xml = new SimpleXMLElement('records.xml', 0, true);
// This will work as expected because its a hard coded property value
foreach($xml as $record){
echo $record->id; // Will output the ID fine
}
// Dynamic properties require typecasting to string
$xml_field = 'id';
foreach($xml as $record){
// This will dump a SimpleXMLElement object
var_dump($record->$xml_field);
// This will output the value as expected
echo (string)$record->$xml_field;
}
?>
备份地址:http://www.lvesu.com/blog/php/simplexmlelement.construct.php