SimpleXMLElement::asXML

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::asXML Return a well-formed XML string based on SimpleXML element

说明

public SimpleXMLElement::asXML ( string|null $filename = null ) : string|bool

The asXML method formats the parent object's data in XML version 1.0.

参数

filename

If a string value is provided, the function writes the data to the file rather than returning it.

返回值

If the filename isn't specified, this function returns a string on success and false on error. If the parameter is specified, it returns true if the file was written successfully and false otherwise.

更新日志

版本 说明
8.0.0 filename is nullable now.

范例

Example #1 Get XML

<?php
$string 
= <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

echo 
$xml->asXML();

?>

以上例程会输出:

<?xml version="1.0"?>
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>

asXML also works on Xpath results:

Example #2 Using asXML() on SimpleXMLElement::xpath() results

<?php
// Continued from example XML above.

/* Search for <a><b><c> */
$result $xml->xpath('/a/b/c');

foreach (
$result as $node) {
    echo 
$node->asXML();
}
?>

以上例程会输出:

<c>text</c><c>stuff</c>

参见

User Contributed Notes

andreas dot theissen at t-online dot de 27-Oct-2012 12:37
To prevent asXML from encoding vowels unwantedly, simply use an approriate XML header with encoding in advance.

If you do so, asXML will happily leave your vowels (and the header) entirely untouched.

<?php

$xmlstr
=
'<?xml version="1.0" encoding="UTF-8"?>
<keys>
  <key lang="en">&lt;Insert&gt;</key>
  <key lang="de">&lt;Einfügen&gt;</key>
</keys>'
;

$sxe = new SimpleXMLElement($xmlstr);

$output = $sxe->asXML();

?>

$xmlstr and $output are identical now.

The subsequent use of html_entity_decode() (as proposed in the very beginning in another post) has several drawbacks:

1. It is slow
2. It is expensive
3. If there are already encoded arrow brackets or double quotes in your source for instance (as shown in the above example), markup will be broken.
oleg dot pavlin at gmail dot com 10-Jan-2012 04:17
Function asXML decodes special chars like ?, ? and others to &#xE6;, &#xF8;

To get normal output use without quoting:

$xml = html_entity_decode($xml, ENT_NOQUOTES, 'UTF-8');
jcr at di dot uminho dot pt 25-Jan-2011 02:32
Code snippet to load a XML document, increment an attribute and store it again.
My XML looks like:
<?xml version="1.0" encoding="ISO-8859-1"?>
<doctypes counter="16">
    <doctype id="d1">
        <name>Carta</name>
        <acro>CA</acro>
    </doctype>
...
</doctypes>

I want to retrieve the counter attribute, increment it, and store the new document at the end:

<?php
  $document
= simplexml_load_file("mydoc.xml");
 
$cont = (integer) $document['counter'];
 
$document['counter'] = $cont+1;
 
$document->asXML("mydoc.xml");
?>
PHP8中文手册 站长在线 整理 版权归PHP文档组所有