我使用的是PHP v5.3。我想將字符串轉換爲有效的xml。 Xml顯然需要將'&'字符編碼爲&
,但我可以找到的所有函數都會將'ë'轉換爲html實體xml不接受(在這種情況下爲ë
)。我應該使用什麼功能?PHP字符串到XML
回答
htmlspecialchars
是你所需要的。與htmlentities
不同,它的選擇性更強,而不是它的轉換。
從htmlentities
documentation:
此功能是相同的用htmlspecialchars()在所有的方法,除了用 ヶ輛(),它們具有HTML字符實體 等同物被翻譯成這些實體的所有字符。
<?php
$a = "I love things & stuffë";
$b = htmlspecialchars($a);
$c = htmlentities($a);
echo "$b\n$c\n";
輸出:
I love things & stuffë
I love things & stuffë
$str = preg_replace('/\s&\s/', '&', $str);
這將取代所有'&'包圍尾隨和結束的空白。只要制定出的圖案有點,因爲你需要
謝謝,將工作確實,但我不確定是否是唯一需要編碼的字符。 – 2013-03-15 16:46:36
如果你只是想轉換&到&
你可以試試這個:
$encoded_str = str_replace('&','&',$original_str);
要避免遇到類似&amp;
如果你原來有一個&
,單程以防止它是將所有&
到&第一
$encoded_str = str_replace('&','&',str_replace('&','&',$original_str));
謝謝,確實會工作,但我不確定是否&是唯一需要編碼的字符。 – 2013-03-15 16:46:59
如果創建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 & but all functions I can find which do this also convert characters like 'ë' to html entities xml doesn't accept (ë 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 '&' 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?
- 1. PHP字符串到XML文件
- 2. PHP解析XML字符串
- 3. XML到字符串值
- 4. linq到XML字符串
- 5. NSDictionary到XML字符串
- 6. 字符串到Xml轉換
- 7. Node.js NodeList到XML字符串
- 8. plist XML字符串到NSMutableDictionary
- 9. 解析:字符串到XML
- 10. XML字符串到文件
- 11. 讀取XML字符串在PHP
- 12. 從PHP這個XML字符串
- 13. 從php中創建XML字符串
- 14. PHP - 字符串到html
- 15. PHP int到字符串
- 16. 得到的字符串PHP
- 17. 字符串到時間PHP
- 18. PHP對象到字符串
- 19. 轉換詞典<字符串,字符串>到XML
- 20. 字符串在XML
- 21. 無法使用PHP將xml字符串發佈到webservice
- 22. PUT字符串的數據到XML服務器使用PHP
- 23. Java&XML - 帶有至XML的字符串的字符串
- 24. 字符串PHP
- 25. PHP:字符串
- 26. PHP:字符串
- 27. PHP字符串
- 28. DataSet.DataTable.DataRow(單個)到XML字符串
- 29. ASP.NET 3.5綁定到XML字符串
- 30. XML值不會讀取到字符串
問題是,如果他導出XML,htmlspecialchars會不會轉換標記<>和其他字符? – aleation 2013-03-15 16:20:17
這就是我所需要的,我認爲,謝謝。 Htmlspecialchars會轉換<>但這沒有問題,因爲它不是一個XML字符串,它只需要是有效的XML。 – 2013-03-15 16:45:59