简体   繁体   English

我可以告诉我的 php 函数在“file_get_contents”使用 php 代码中的 javascript 加载页面之前不执行吗?

[英]Can I tell my php function to not execute until the "file_get_contents" has loaded the page using javascript in php code?

This is my php function:这是我的 php 函数:

$result = file_get_contents('https://www.example.com/index.php'); 
$regex = '/<img class="pic" src="(.*?)">/';   
preg_match($regex, $result, $matches);
 return($matches[1]);

it's a function to get a picture from that link, sometimes it return the picture, sometimes not, because the image in the site sometimes take seconde to load sometimes not.这是从该链接获取图片的功能,有时它返回图片,有时不返回,因为站点中的图像有时需要第二次加载有时不会。 I want to prevent that from happening in my function, I want to delay the return until the image is loaded, i know this is not possible with php, sleep() didn't help, so I know that I must do it with javascript, but I don't know how to do it, please help ty!我想防止在我的函数中发生这种情况,我想延迟返回直到图像加载,我知道这用 php 是不可能的,sleep() 没有帮助,所以我知道我必须用 javascript 来做,但我不知道该怎么做,请帮助您!

If you'd like to load something asynchronously, I guess the simplest solution would be to launch another request from the client side, eg:如果您想异步加载某些内容,我想最简单的解决方案是从客户端启动另一个请求,例如:

  1. Load the page without the desired picture加载没有所需图片的页面
  2. Create a new script, that would be fetching that image URL on the server.创建一个新脚本,它将在服务器上获取该图像 URL。 Let's call in fetch-image.php for example.例如,让我们调用fetch-image.php
  3. Make sure your script will render the image and return correct Content-Type header.确保您的脚本将呈现图像并返回正确的Content-Type标头。 Samplescan be found here .样品可以在这里找到 For that your code will need modification, please see below.为此,您的代码需要修改,请参见下文。
  4. Move your code, mentioned above to the new script将上面提到的代码移动到新脚本中
  5. Replace the image src="/fetch-image.php" attribute with the path to the fetch script将图像src="/fetch-image.php"属性替换为获取脚本的路径

Modified script:修改后的脚本:

$result = file_get_contents('https://www.example.com/index.php'); 
$regex = '/<img class="pic" src="(.*?)">/';   
preg_match($regex, $result, $matches);
echo file_get_contents($matches[1]);

Hope that helps.希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM