转换为& PHP中的XML
问题描述:
我正在为我的页面构建一个XML RSS。而遇到了此问题:转换为& PHP中的XML
error on line 39 at column 46: xmlParseEntityRef: no name
显然,这是因为我不能在XML & ......我在我的最后一个字段一行做...
什么是清洁的最佳途径我所有的在PHP $row['field']'s
使&的变成&
答
使用
html_entity_decode($row['field']);
这将需要从&恢复到&此外,如果有&npsb;它会改变一个空间。
http://us.php.net/html_entity_decode
干杯
答
真的应该在DOM XML函数在PHP。它有点工作要弄清楚,但是你避免了这样的问题。
答
转换保留XML字符实体
function xml_convert($str, $protect_all = FALSE)
{
$temp = '__TEMP_AMPERSANDS__';
// Replace entities to temporary markers so that
// ampersands won't get messed up
$str = preg_replace("/&#(\d+);/", "$temp\\1;", $str);
if ($protect_all === TRUE)
{
$str = preg_replace("/&(\w+);/", "$temp\\1;", $str);
}
$str = str_replace(array("&","<",">","\"", "'", "-"),
array("&", "<", ">", """, "'", "-"),
$str);
// Decode the temp markers back to entities
$str = preg_replace("/$temp(\d+);/","&#\\1;",$str);
if ($protect_all === TRUE)
{
$str = preg_replace("/$temp(\w+);/","&\\1;", $str);
}
return $str;
}
XML不共享所有相同* *命名实体为HTML的 - 仅具有5预定义的实体(安培,LT,GT,quot和apos)。除非XML文档具有包含所有HTML命名实体的DTD,否则使用htmlentities()可以将某些字符转换为XML分析器不需要支持的实体。 – 2009-07-15 17:12:53
那么最好用什么呢? – ian 2009-07-15 17:52:38
@ian:鉴于Gumbo对`htmlspecialcharacters()`的描述,我会去那里(因为它只涉及5个字符和XML中的预定义实体) – 2009-07-15 19:07:14