开发者

Stream context create not showing correct ouput?

开发者 https://www.devze.com 2023-01-31 04:50 出处:网络
I am connecting up to an API and as a result it should loop and output 5开发者_StackOverflow中文版 iterations of the results from the checks.

I am connecting up to an API and as a result it should loop and output 5开发者_StackOverflow中文版 iterations of the results from the checks.

The code

<?php

      $i = 0;

$opts = array(
  'https'=>array(
    'method'=>"POST",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

$fp = fopen('https://ssl.theapidomain.com.au/check.php?domain=testdomain&suffixes=com.au', 'r', false, $context);

    while ($i < 5) {
      fpassthru($fp);
      $out = explode('<br>', $fp);
      echo $out[0];
      echo "<br>";
      echo $out[1];
      echo "<br>";
      echo date('H:i:s');
      echo "<br>";
      $i++;
    }

fclose($fp);

?>

The output

available: testdomain.com.au not available: whoisfailure: Resource id #2

16:58:57

Resource id #2

16:58:57

Resource id #2

16:58:57

Resource id #2

16:58:57

Resource id #2

16:58:57

It should be outputting this 5 times:

available: testdomain.com.au not available: 16:58:57

It seems when I echo $out[0] and [2], it displays the resource id rather than the information inside (available / not available).


You must use fread() on that filepointer $fp, not fpassthru(). You'll get a string result from fread which you can then feed into explode(). Otherwise explode just reads the $fp which outputs nothing but Resource #123.

 $html = fread($fp, 16384);
 $out = explode("<br>", $html);

Btw, you should stop trying to microoptimize your domain query thing. The bottleneck is the network traffic, not making the loop run faster. The PHP stream wrapper isn't faster than cURL.

0

精彩评论

暂无评论...
验证码 换一张
取 消