如何加快file_get_contents? [英] How to speed up file_get_contents?

查看:70
本文介绍了如何加快file_get_contents?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

$language = $_GET['soundtype'];
$word = $_GET['sound'];
$word = urlencode($word);
if ($language == 'english') {
    $url = "<the first url>";
} else if ($language == 'chinese') {
    $url = "<the second url>";
}
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"User-Agent: <my user agent>"
  )
);
$context = stream_context_create($opts);
$page = file_get_contents($url, false, $context);
header('Content-Type: audio/mpeg');
echo $page;

但是我发现运行速度非常慢.

But I've found that this runs terribly slow.

有没有可能的优化方法?

Are there any possible methods of optimization?

注意: $url是一个远程URL.

Note: $url is a remote url.

推荐答案

之所以很慢,是因为file_get_contents()将整个文件读入$page,PHP在输出内容之前等待文件被接收.因此,您要做的是:在服务器端下载整个文件,然后将其作为单个大字符串输出.

It's slow because file_get_contents() reads the entire file into $page, PHP waits for the file to be received before outputting the content. So what you're doing is: downloading the entire file on the server side, then outputting it as a single huge string.

file_get_contents()不支持流或获取远程文件的偏移量.一种选择是使用 fsockopen() 创建原始套接字,执行HTTP请求,并循环读取响应,当您读取每个块时,将其输出到浏览器.这样会更快,因为将流式传输文件.

file_get_contents() does not support streaming or grabbing offsets of the remote file. An option is to create a raw socket with fsockopen(), do the HTTP request, and read the response in a loop, as you read each chunk, output it to the browser. This will be faster because the file will be streamed.

手册中的示例

$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {

    header('Content-Type: audio/mpeg');

    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}

以上内容在仍然有可用内容的情况下循环播放,在每次迭代中它读取128个字节,然后将其输出到浏览器.相同的原则适用于您所做的事情.您需要确保不输出响应HTTP标头,因为它是前几行,因为由于您正在执行原始请求,因此您将获得包含标头的原始响应.如果输出响应头,则会导致文件损坏.

The above is looping while there is still content available, on each iteration it reads 128 bytes and then outputs it to the browser. The same principle will work for what you're doing. You'll need to make sure that you don't output the response HTTP headers which will be the first few lines, because since you are doing a raw request, you will get the raw response with headers included. If you output the response headers you will end up with a corrupt file.

这篇关于如何加快file_get_contents?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆