2009-07-15 49 views
3

我正在为我的页面构建一个XML RSS。而遇到了此问题:转换为& PHP中的XML

error on line 39 at column 46: xmlParseEntityRef: no name 

显然,这是因为我不能在XML & ......我在我的最后一个字段一行做...

什么是清洁的最佳途径我所有的在PHP $row['field']'s使&的变成&

回答

8

使用htmlspecialchars只是个编码e HTML特殊字符&,<,>,"和可选的'(参见第二参数$quote_style)。

1

这就是所谓的htmlentities()html_entity_decode()

+3

XML不共享所有相同* *命名实体为HTML的 - 仅具有5预定义的实体(安培,LT,GT,quot和apos)。除非XML文档具有包含所有HTML命名实体的DTD,否则使用htmlentities()可以将某些字符转换为XML分析器不需要支持的实体。 – 2009-07-15 17:12:53

+0

那么最好用什么呢? – ian 2009-07-15 17:52:38

+0

@ian:鉴于Gumbo对`htmlspecialcharacters()`的描述,我会去那里(因为它只涉及5个字符和XML中的预定义实体) – 2009-07-15 19:07:14

2

真的应该在DOM XML函数在PHP。它有点工作要弄清楚,但是你避免了这样的问题。

1

转换保留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("&amp;", "&lt;", "&gt;", "&quot;", "&apos;", "&#45;"), 
         $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; 
}