【问题标题】:file_get_contents get data after 5 second from loading the web-pagefile_get_contents 在加载网页 5 秒后获取数据
【发布时间】:2018-11-27 16:25:03
【问题描述】:

我想检查源网页是否在 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");

有什么想法吗?

【问题讨论】:

  • $url 设置在哪里?此外,您缺少报价,因此代码将无法正常工作,并且希望该页面没有其他的买卖实例,您最好使用 dom 解析器正确抓取它,例如domdocument
  • 如果您需要在请求数据之前加载页面,您将无法在 1 个请求中完成 - 您最好的选择是通过 js 将请求发送到实际执行的 php 脚本文件获取内容
  • “5 秒后”不太可能是这样工作的。您将按原样获得基本 HTML。您更有可能观察到一些延迟的 AJAX 请求。请参阅浏览器 devtools / F12 和网络选项卡。

标签: php file-get-contents


【解决方案1】:

如果您需要在请求数据之前加载页面,您将无法在 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>

【讨论】:

  • 我应该更改
  • @Dr.Mezo 差不多 - 您需要向用户显示该数据,但如何做到这一点完全取决于 HTML。我会相应地更新答案。
【解决方案2】:

你应该使用 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-18
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多