PHP 要擷取其他網頁的資料,最方便的方法是用 file_get_contents() 函式,以下程式碼即可完成:
1 2 3 |
<?php $data = file_get_contents("https://www.google.com.hk"); ?> |
如果使用量不高,那麼用 file_get_contents() 沒什麼問題,但如果 PHP 擷取其他網頁內容的頻率很高,便建議改用 curl 完成了。因為 curl 的效率比 file_get_contents() 高,以下是 curl 的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php ### load url contents function function load_contents($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch); curl_close($ch); return $data; } $data = url_contents("https://www.google.com.hk"); ?> |
第二個範例是不是有寫錯呢?
$data = load_contents(“https://www.google.com.hk”);
謝謝提醒, 已經改好了.