简体   繁体   中英

Creating PHP -> XML with special character '&'

I'm trying to create an XML from PHP with special characters.

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ' . 'standalone="yes"?><Root/>');

$data->addChild('NAME', $variable);

$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;     
$dom->formatOutput = true;
$dom->loadXML($xmlAusgabe = $xml->asXML());
$dom->save('../test.xml');

When there is a special character like '&' in it the output is empty.

I thought these characters are available in UTF-8.

Can someone help me?

When embed XML, always there are many problems :( try this:

Change

$dom->loadXML($xmlAusgabe = $xml->asXML());

by

$xmlAusgabe = $xml->asXML();
$xmlAusgabe = mb_convert_encoding( $xmlAusgabe, 'HTML-ENTITIES',  'UTF-8') ;
$dom->loadXML( $xmlAusgabe );

Then check encoding and fileencoding is utf8 . If you use vim editor:

set encoding=utf-8
set fileencoding=utf-8

UPDATE

libxml_use_internal_errors( FALSE );

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Root/>');

$data->addChild('NAME', mb_convert_encoding( $variable, 'HTML-ENTITIES',  'UTF-8') );

$xmlAusgabe = $xml->asXML();

$dom = new DOMDocument();
$dom->loadXML( $xmlAusgabe );
$dom->save('../test.xml');

I check this code and run. To print error use:

libxml_get_errors()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM