問題描述
我正在嘗試從 Twitter 嵌入推文.所以,我使用 cURL 來取回 json.我寫了一個(gè)小測(cè)試,但測(cè)試大約需要 5 秒,當(dāng)我在本地運(yùn)行時(shí).所以,我不確定我在這里做錯(cuò)了什么.
I'm trying to get embed tweet from Twitter. So, I'm using cURL to get the json back. I wrote a little test but the test takes around 5 seconds as well as when I run locally. So, I'm not sure what am I doing wrong here.
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;
}
當(dāng)我粘貼鏈接并從瀏覽器進(jìn)行測(cè)試時(shí),速度非常快.
When I paste the link and test it from the browser it's really fast.
推薦答案
關(guān)于環(huán)境,我在 PHP 中觀察到,cURL 通常在大多數(shù)環(huán)境中運(yùn)行得非常快,除了在 CPU 低且網(wǎng)絡(luò)較慢的地方表現(xiàn).例如,在我的 MAMP 安裝的 localhost 上,curl 很快,在較大的亞馬遜實(shí)例上,curl 很快.但是在一個(gè)糟糕的小型主機(jī)上,我看到它存在性能問題,連接速度明顯變慢.不過,我不確定為什么會(huì)變慢.此外,它肯定不會(huì)慢 5 秒.
With respect to environment, I've observed in PHP that cURL typically runs very fast in most environments except in places where there is low CPU and there is slower network performance. For example, on localhost on my MAMP installation, curl is fast, on a larger amazon instance, curl is fast. But on a small crappy hosting, i've seen it have performance issues where it is noticeably slower to connect. Though, i'm not sure exactly why that is slower. Also, it sure wasn't 5 seconds slower.
為了幫助確定是 PHP 還是您的環(huán)境,您應(yīng)該嘗試通過命令行與 curl 交互.至少,如果還有 5 秒,您就可以排除 PHP 代碼的問題.
to help determine if its PHP or your environment, you should try interacting with curl via the command line. At least that you'll be able to rule out PHP code being the problem if its still 5 seconds.
這篇關(guān)于如何加速php中的cURL?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!