使SimpleXMLElement在输出中包含编码 [英] Getting SimpleXMLElement to include the encoding in output

查看:149
本文介绍了使SimpleXMLElement在输出中包含编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是:

  $ XML = new SimpleXMLElement(< foo />); 
echo($ XML-> asXML());

...输出:

 <?xml version =1.0?> 
< foo />

但是我想要输出编码:

 <?xml version =1.0encoding =UTF-8?> 
< foo />

有没有办法告诉SimpleXMLElement包含<?xml?>标签的encoding属性?除此之外:

  $ XML = new SimpleXMLElement(<?xml version ='1.0'encoding ='utf- 8'?>< foo />); 
echo($ XML-> asXML());

哪些有用,但是必须手动指定版本和编码是令人讨厌的。



假设为了这个问题的目的,我不能使用DOMDocument。

解决方案

你可以尝试这个,但是您必须使用 simplexml_load_string $ xml

  $ xml //您的主要SimpleXMLElement 
$ xml-> addAttribute('encoding','UTF-8');

或者您仍然可以使用其他方法将编码添加到输出。



简单替换

  $ outputXML = str_replace(' ?xml version =1.0?>','<?xml version =1.0encoding =UTF-8?>',$ outputXML) 

正则表达式

  $ outputXML = preg_replace('/< \?\s * xml([^ \s] *)\?> /''<?xml $ 1 encoding =UTF-8?>',$ outputXML); 

DOMDocument - 我知道你说你不想使用DOMDocument,但这里是一个例子

  $ xml = dom_import_simplexml($ simpleXML); 
$ xml-> xmlEndoding ='UTF-8';
$ outputXML = $ xml-> saveXML();

您可以将此代码包装到接收参数$ encoding的函数中,并将其添加到


This:

$XML = new SimpleXMLElement("<foo />");
echo($XML->asXML());

...outputs this:

<?xml version="1.0"?>
<foo/>

But I want it to output the encoding, too:

<?xml version="1.0" encoding="UTF-8"?>
<foo/>

Is there some way to tell SimpleXMLElement to include the encoding attribute of the <?xml?> tag? Aside from doing this:

$XML = new SimpleXMLElement("<?xml version='1.0' encoding='utf-8'?><foo />");
echo($XML->asXML());

Which works, but it's annoying to have to manually specify the version and encoding.

Assume for the purposes of this question that I cannot use DOMDocument instead.

解决方案

You can try this, but you must use simplexml_load_string for $xml

$xml // Your main SimpleXMLElement
$xml->addAttribute('encoding', 'UTF-8');

Or you can still use other means to add the encoding to your output.

Simple Replacement

$outputXML=str_replace('<?xml version="1.0"?>', '<?xml version="1.0" encoding="UTF-8"?>', $outputXML);

Regular Expressions

$outputXML=preg_replace('/<\?\s*xml([^\s]*)\?>/' '<?xml $1 encoding="UTF-8"?>', $outputXML);

DOMDocument - I know you said you don't want to use DOMDocument, but here is an example

$xml=dom_import_simplexml($simpleXML);
$xml->xmlEndoding='UTF-8';
$outputXML=$xml->saveXML();

You can wrap this code into a function that receives a parameter $encoding and adds it to the

这篇关于使SimpleXMLElement在输出中包含编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆