在php中格式化xml属性的字符串 [英] Formatting string for xml attribute in php

查看:84
本文介绍了在php中格式化xml属性的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些在我的数据库中有效的字符串,但是当我将它们包含在UTF-8 XML输出的属性中时,它们给我以下错误:


XML解析错误:格式不正确


我目前的代码(简化):

  header('Content-Type:text / xml'); 
echo'<?xml version =1.0encoding =UTF-8standalone =yes?>';
echo'< root attribute ='。htmlentities($ string_from_hell)。'>';

在将这些字符串包含在XML属性中之前,我应该如何格式化这些字符串?



$ string_from_hell 可能的值:œ(不知道是否将正确显示)

解决方案

尝试

 code> htmlspecialchars($ string_from_hell,ENT_QUOTES,UTF-8)

htmlentities 不会这样做,因为它将创建不能在XML中识别的HTML实体,而只能HTML。您还应该指定字符集,因为默认值不是UTF-8,它是ISO-8859-1。



您还缺少引号()。



还有更好的方法来创建处理转义的XML文件,例如 XMLWriter


I have some strings that are valid in my database but when I include them in an attribute of a UTF-8 XML output they give me the following error:

XML Parsing Error: not well-formed

My current code (simplified):

header('Content-Type: text/xml'); 
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<root attribute="' . htmlentities($string_from_hell) . '">'; 

How should I format these strings before including them in XML attributes?

A possible value for $string_from_hell:  (don't know if it will show up properly)

解决方案

Try

htmlspecialchars($string_from_hell, ENT_QUOTES, "UTF-8")

htmlentities won't do because it will create HTML entities that are not recognized in XML, only HTML. You should also specify the charset because the default is not UTF-8, it's the ISO-8859-1.

You're also missing the quotes (") around the attribute value.

There are also better ways to create XML files that handle escaping for you. See e.g. XMLWriter.

这篇关于在php中格式化xml属性的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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