2013-03-15 134 views
0

我使用的是PHP v5.3。我想將字符串轉換爲有效的xml。 Xml顯然需要將'&'字符編碼爲&,但我可以找到的所有函數都會將'ë'轉換爲html實體xml不接受(在這種情況下爲ë)。我應該使用什麼功能?PHP字符串到XML

回答

4

htmlspecialchars是你所需要的。與htmlentities不同,它的選擇性更強,而不是它的轉換。

htmlentitiesdocumentation

此功能是相同的用htmlspecialchars()在所有的方法,除了用 ヶ輛(),它們具有HTML字符實體 等同物被翻譯成這些實體的所有字符。

<?php 
$a = "I love things & stuffë"; 
$b = htmlspecialchars($a); 
$c = htmlentities($a); 
echo "$b\n$c\n"; 

輸出:

I love things &amp; stuffë 
I love things &amp; stuff&Atilde;&laquo; 

http://www.php.net/manual/en/function.htmlspecialchars.php

+0

問題是,如果他導出XML,htmlspecialchars會不會轉換標記<>和其他字符? – aleation 2013-03-15 16:20:17

+0

這就是我所需要的,我認爲,謝謝。 Htmlspecialchars會轉換<>但這沒有問題,因爲它不是一個XML字符串,它只需要是有效的XML。 – 2013-03-15 16:45:59

0
$str = preg_replace('/\s&\s/', '&amp', $str); 

這將取代所有'&'包圍尾隨和結束的空白。只要制定出的圖案有點,因爲你需要

+0

謝謝,將工作確實,但我不確定是否是唯一需要編碼的字符。 – 2013-03-15 16:46:36

0

如果你只是想轉換&到&amp;你可以試試這個:

$encoded_str = str_replace('&','&amp;',$original_str); 

要避免遇到類似&amp;amp;如果你原來有一個&amp;,單程以防止它是將所有&amp;到&第一

$encoded_str = str_replace('&','&amp;',str_replace('&amp;','&',$original_str)); 
+0

謝謝,確實會工作,但我不確定是否&是唯一需要編碼的字符。 – 2013-03-15 16:46:59

2

如果創建XML,你可能有一個DOMDocument在眼前了。即使沒有,你也可以輕鬆創建一個。隨着DOMDocument您可以創建文本,100%以及形成對XML:

$text = "I'm using php v5.3. I would like to convert a string to valid xml. Xml apparently requires '&' characters to be encoded to &amp; but all functions I can find which do this also convert characters like 'ë' to html entities xml doesn't accept (&euml; in this case). What function should I use?"; 

$doc = new DOMDocument(); 
echo $doc->saveXML($doc->createTextNode($text)); 

這給你下面的輸出(逐字):

I'm using php v5.3. I would like to convert a string to valid xml. Xml apparently requires '&amp;' characters to be encoded to &amp;amp; but all functions I can find which do this also convert characters like 'ë' to html entities xml doesn't accept (&amp;euml; in this case). What function should I use?