2016-12-15 81 views
0

我正在使用下面的google建議查詢並返回xml格式輸出,在此輸出中它包含特殊或其他語言字符。xml simplexml_load_file不解析特殊或其他語言字符

http://suggestqueries.google.com/complete/search?output=toolbar&hl=en&q=facebook+e 

它給下面的XML格式輸出...

<toplevel> 
<CompleteSuggestion> 
<suggestion data="facebook en español"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="facebook emojis"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="facebook event photo size"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="facebook emoticons"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="facebook email"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="facebook events"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="facebook earnings"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="facebook earnings date"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="facebook email address"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="facebook event banner size"/> 
</CompleteSuggestion> 
</toplevel> 

當我使用下面的代碼加載這個XML文件的foreach我得到錯誤...

foreach ($xml->children() as $child) { 
foreach ($child->suggestion->attributes() as $dta) { 
echo "<br>"; 
echo $dta; 
} 
} 

輸出下面得到錯誤信息......

Warning: simplexml_load_file(): 
http://suggestqueries.google.com/complete/search? 
output=toolbar&hl=en&q=facebook.'%20'.e:1: parser error : Input is not 
proper UTF-8, indicate encoding ! Bytes: 0xF1 0x6F 0x6C 0x22 in 

Warning: simplexml_load_file(): es"/></CompleteSuggestion> 
<CompleteSuggestion><suggestion data="facebook en espa in 

回答

0

在嘗試解析它之前,您應該在UTF-8中編碼google建議查詢的響應。

$encodedResponse = utf8_encode(file_get_contents('http://suggestqueries.google.com/complete/search?output=toolbar&hl=en&q=facebook+e')); 
$xml = simplexml_load_string($encodedResponse); 
+0

嗨Arnaud,謝謝 –

+0

不客氣。我可以請你加入我的答案嗎?謝謝。 –