file_get_contents在加载网页5秒后获取数据

时间:2018-11-27 16:25:04

标签: php file-get-contents

我想检查源网页在PHP中是否有特定单词,但是网页在5秒后加载

尝试了经典方式,但由于立即加载页面而无法正常工作

    <?php
   $urlmain = "http://example.com";
    $url = file_get_contents("$urlmain");
    if (strpos($url, 'buy') !== false) {
        $pid= 'Available';

    }elseif (strpos($url, 'sold') !== false) {
        $pid= 'Sold';

    }else{ 
               $pid= 'can't get data';
    }

     echo $pid;

    ?>

在之前的代码中,我希望file_get_contents在加载网页5秒后获取数据

$ url = file_get_contents(“ $ url”);

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

如果您需要在请求数据之前加载页面,则将无法在1个请求中完成。

您最好的选择是正常加载页面(不添加任何file_get_contents),等待5秒钟,通过JS向实际执行file_get_contents的PHP脚本发送请求。请注意,您的代码应以die();结尾,否则,您的第二个请求将在您的结果顶部显示整个页面。

尝试以下操作:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

  // This is your code to get data

  $url = file_get_contents("$url");
  if (strpos($url, 'buy') !== false) {
    $pid = 'Available';

  } elseif (strpos($url, 'sold') !== false) {
    $pid = 'Sold';

  } else {
    $pid = 'can\'t get data';
  }

  echo $pid;
  die();
}
?>
<div id="output"></div>
<script>
    // On page load we start counting for 5 seconds, after which we execute function
    window.onload = setTimeout(function (){
        // We prepare AJAX request to the same PHP script, but via POST method
        var http = new XMLHttpRequest();
        var url = '';
        http.open('POST', url, true);

        http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

        // When we get back successful results, we will output them to HTML node with ID = output
        http.onreadystatechange = function() {
            if(http.readyState === 4 && http.status === 200) {
                document.getElementById('output').innerHTML = http.responseText;
            }
        }
        http.send();
    }, 5000);
</script>

答案 1 :(得分:-1)

您应该使用PHP cURL扩展名:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
curl_close($ch);