Heim  >  Artikel  >  Backend-Entwicklung  >  php字符转码解决新浪抓取资料乱码的问题

php字符转码解决新浪抓取资料乱码的问题

WBOY
WBOYOriginal
2016-07-25 08:53:37867Durchsuche
  1. function unescape($str) {
  2. $str = rawurldecode($str);
  3. preg_match_all("/(?:%u.{4})|.+/",$str,$r);
  4. $ar = $r[0];
  5. foreach($ar as $k=>$v) {
  6. if(substr($v,0,2) == '%u' && strlen($v) == 6)
  7. $ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,-4)));
  8. }
  9. return join("",$ar);
  10. }
复制代码

有点小问题,又换一个函数,好像功能要强大一些。

  1. function unescape($str) {
  2. $str = rawurldecode($str);
  3. preg_match_all("/%u.{4}|.{4};|\d+;|\d+?|.+/U",$str,$r);
  4. $ar = $r[0];
  5. foreach($ar as $k=>$v) {
  6. if(substr($v,0,2) == "%u")
  7. $ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,-4)));
  8. elseif(substr($v,0,3) == "")
  9. $ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,3,-1)));
  10. elseif(substr($v,0,2) == "") {
  11. $ar[$k] = iconv("UCS-2","utf-8",pack("n",preg_replace("/[^\d]/","",$v)));
  12. }
  13. }
  14. return join("",$ar);
  15. }
复制代码

用了一段时间,发现在本地可以使用,但是我们的线上环境不能够使用。 线上是*nux,本地是XP了,还有,就是PHP版本不一样了。 后来,又在手册里面发现有一个类似的函数 而且还支持utf8,个人觉得应该通用性更好吧。

  1. //php字符转码
  2. function utf8RawUrlDecode ($source) {
  3. $decodedStr = "";
  4. $pos = 0;
  5. $len = strlen ($source);
  6. while ($pos $charAt = substr ($source, $pos, 1);
  7. if ($charAt == '%') {
  8. $pos++;
  9. $charAt = substr ($source, $pos, 1);
  10. if ($charAt == 'u') {
  11. // we got a unicode character
  12. $pos++;
  13. $unicodeHexVal = substr ($source, $pos, 4);
  14. $unicode = hexdec ($unicodeHexVal);
  15. $entity = "". $unicode . ';';
  16. $decodedStr .= utf8_encode ($entity);
  17. $pos += 4;
  18. }
  19. else {
  20. // we have an escaped ascii character
  21. $hexVal = substr ($source, $pos, 2);
  22. $decodedStr .= chr (hexdec ($hexVal));
  23. $pos += 2;
  24. }
  25. } else {
  26. $decodedStr .= $charAt;
  27. $pos++;
  28. }
  29. }
  30. return $decodedStr;
  31. }
复制代码

使用此函数成功解决问题。



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn