PHP file_put_contents亚洲字符文件名编码


php file_put_contents asian character filename encoding

我正在尝试从维基百科上获取这些图片。免费授权媒体有什么用?原文在这里

如果你把这个

http://upload.wikimedia.org/wikipedia/commons/2/26/%E7%9A%84-bw.png

在firefox中,它会立即转换成

http://upload.wikimedia.org/wikipedia/commons/2/26/

这样当你保存图像时,它就会被保存为。-bw.png

很简单吧?如何让php这样做呢?只是猜测,我尝试了utf8_decode($fileName) ..但是读错了汉字。

$src= "http://upload.wikimedia.org/wikipedia/commons/2/26/%E7%9A%84-bw.png";  
$pngData = file_get_contents($src);  
$fileName = basename($src);  
file_put_contents($fileName, $pngData);

谢谢你的帮助,因为我真的不知道从这里去哪里。

您试过url_decode();吗?

<?php
$url = 'http://upload.wikimedia.org/wikipedia/commons/2/26/%E7%9A%84-bw.png';
$parts = explode('/', $url);
$title = $parts[count($parts)-1]; //get last section
$title = urldecode($title);
?>

Squirrelmail在源代码中包含一个很好的函数,用于将unicode转换为实体:

<?php 
function charset_decode_utf_8 ($string) { 
       /* Only do the slow convert if there are 8-bit characters */ 
     /* avoid using 0xA0 ('240) in ereg ranges. RH73 does not like that */ 
     if (! ereg("['200-'237]", $string) and ! ereg("['241-'377]", $string)) 
         return $string; 
     // decode three byte unicode characters 
     $string = preg_replace("/(['340-'357])(['200-'277])(['200-'277])/e",        
     "'&#'.((ord('''1')-224)*4096 + (ord('''2')-128)*64 + (ord('''3')-128)).';'",    
     $string); 
     // decode two byte unicode characters 
     $string = preg_replace("/(['300-'337])(['200-'277])/e", 
     "'&#'.((ord('''1')-192)*64+(ord('''2')-128)).';'", 
     $string); 
     return $string; 
 } 
?>