gpt4 book ai didi

php - 如何在 php 中加速 cURL?

转载 作者:可可西里 更新时间:2023-10-31 22:52:47 31 4
gpt4 key购买 nike

我正在尝试从 Twitter 获取嵌入推文。所以,我正在使用 cURL 取回 json。我写了一个小测试,但测试需要大约 5 秒,就像我在本地运行时一样。所以,我不确定我在这里做错了什么。

public function get_tweet_embed($tw_id) {

$json_url = "https://api.twitter.com/1/statuses/oembed.json?id={$tw_id}&align=left&omit_script=true&hide_media=false";

$ch = curl_init( $json_url );
$start_time = microtime(TRUE);
$JSON = curl_exec($ch);
$end_time = microtime(TRUE);
echo $end_time - $start_time; //5.7961111068726

return $this->get_html($JSON);
}

private function get_html($embed_json) {
$JSON_Data = json_decode($embed_json,true);
$tw_embed_code = $JSON_Data["html"];
return $tw_embed_code;
}

当我粘贴链接并从浏览器对其进行测试时,速度非常快。

最佳答案

我曾经获得的最佳加速是重复使用相同的 curl 句柄。将 $ch = curl_init( $json_url ); 替换为 curl_setopt($ch, CURLOPT_URL, $url);。然后在函数外有一个 $ch = curl_init();。您需要在函数中将 $ch 设为全局才能访问它。

重复使用 curl 句柄可保持与服务器的连接打开。仅当请求之间的服务器与您的服务器相同时,这才有效。

关于php - 如何在 php 中加速 cURL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19467449/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com