2011-07-26 50 views
0

這給了我錯誤有錯誤;在str_replace數組?

$illegal = array("&", "<", ">", "\"); 
$legal = array("&amp;", "&lt;", "&gt;", "&quot;"); 

$row['name'] = str_replace($illegal, $legal, $row['name']); 

這是代碼的主要部分

$xml_output = "<?xml version=\"1.0\"?>\n"; 
$xml_output .= "<products>\n"; 

for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){ 
    $row = mysql_fetch_assoc($resultID); 
    $xml_output .= "\t<product>\n"; 
    $xml_output .= "\t\t<id>" . $row['id'] . "</id>\n"; 
     // Escaping illegal characters 
$illegal = array("&", "<", ">", "\"); 
$legal = array("&amp;", "&lt;", "&gt;", "&quot;"); 

$row['name'] = str_replace($illegal, $legal, $row['name']); 


    $xml_output .= "\t\t<name>" . $row['name'] . "</name>\n"; 
    $xml_output .= "\t</product>\n"; 
} 

$xml_output .= "</products>"; 

echo $xml_output; 

我的2個問題是

  1. 是這樣的作品,快於或等於一個代碼塊到第二個?
  2. 如果第二塊更快,我該如何解決?

謝謝。

+0

,哪些錯誤是測試運行速度? ;) –

+0

語法突出顯示在您的帖子上的事實應該指出您的其中一個問題。 – Mat

+0

'$ illegal = array(「&」,「<", ">」,「\」);'在'「\」'處丟失第二個引號。你可以只用''''而不是'「\」「'。 – Wiseguy

回答

4
$illegal = array("&", "<", ">", "\"); 

應該

$illegal = array("&", "<", ">", '"'); 

此外,看看使用htmlspecialchars,而不是你自己的解決方案。

+1

基於'「"」',他想要一個報價'「\」「',而不是斜槓'」\\「'。 – Wiseguy

+0

@Wiseguy:你說得對,我編輯了我的答案,謝謝。 – GWW

+0

謝謝。 +1提及'htmlspecialchars()'和使用單引號 – Wiseguy