目录

PHP __construct() 函数

❮ PHP SimpleXML 参考

示例

从字符串创建 SimpleXMLElement 对象:

<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;

$xml=new SimpleXMLElement($note);
echo $xml->asXML();
?>
运行示例 »

定义和用法

__construct() 函数创建一个新的 SimpleXMLElement 对象。


语法

SimpleXMLElement::__construct( data, options, data_is_url, ns, is_prefix)

参数值

Parameter Description
data Required. Specifies a well-formed XML string or the path or URL to an XML document if data_is_url is TRUE
options Optional. Specifies additional Libxml parameters. Is set by specifying the option and 1 or 0 (TRUE or FALSE, e.g. LIBXML_NOBLANKS(1))

Possible values:

  • LIBXML_COMPACT - Activate nodes allocation optimization (may speed up application)
  • LIBXML_DTDATTR - Set default DTD attributes
  • LIBXML_DTDLOAD - Load external subset
  • LIBXML_DTDVALID - Validate with the DTD
  • LIBXML_NOBLANKS - Remove blank nodes
  • LIBXML_NOCDATA - Merge CDATA as text nodes
  • LIBXML_NOEMPTYTAG - Expand empty tags (e.g. <br/> to <br></br>), only available in the DOMDocument->save() and DOMDocument->saveXML() functions
  • LIBXML_NOENT - Substitute entities
  • LIBXML_NOERROR - Do not show error reports
  • LIBXML_NONET - Disable network access while loading documents
  • LIBXML_NOWARNING - Do not show warning reports
  • LIBXML_NOXMLDECL - Drop the XML declaration when saving a document
  • LIBXML_NSCLEAN - Remove redundant namespace declarations
  • LIBXML_PARSEHUGE - Sets XML_PARSE_HUGE flag, which relaxes any hardcoded limit from the parser. This affects limits like maximum depth of a document and limits of the size of text nodes
  • LIBXML_XINCLUDE - Implement XInclude substitution
  • LIBXML_ERR_ERROR - Get recoverable errors
  • LIBXML_ERR_FATAL - Get fatal errors
  • LIBXML_ERR_NONE - Get no errors
  • LIBXML_ERR_WARNING - Get simple warnings
  • LIBXML_VERSION - Get libxml version (e.g. 20605 or 20617)
  • LIBXML_DOTTED_VERSION - Get dotted libxml version (e.g. 2.6.5 or 2.6.17)
data_is_url Optional. TRUE specifies that data is a path/URL to an XML document instead of string data. Default is FALSE
ns Optional. Specifies a namespace prefix or URI
is_prefix Optional. Specifies a Boolean value. TRUE if ns is a prefix. FALSE if ns is a URI. Default is FALSE


技术细节

返回值: 返回一个 SimpleXMLElement 对象,该对象表示数据
PHP 版本: 5.0+
PHP 变更日志: PHP 5.2.0:添加了可选的纳秒is_前缀参数。
PHP 5.1.2:添加了可选选项数据是网址参数。

更多示例

假设我们有以下 XML 文件,“注释.xml”:

<?xml version="1.0" encoding="UTF-8"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

示例

从 URL 创建 SimpleXMLElement 对象:

<?php
$xml=new SimpleXMLElement("note.xml", 0, TRUE);
echo $xml->asXML();
?>
运行示例 »

❮ PHP SimpleXML 参考