2009-07-15 102 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; 
}