【问题标题】:PHP file_get_contents with multiple urls具有多个 url 的 PHP file_get_contents
【发布时间】:2021-12-28 15:14:39
【问题描述】:

所以基本上我要做的是对于查询生成的每一行,我尝试生成一个 URL 并访问该 URL。有趣的是它总是只访问第一个生成的 URL 而从不访问其他的。

我做错了什么?请帮帮我。

$query = "SELECT distinct b.productname, b.seller, b.price, b.offerid 
          from tracker b";
$results = mysqli_query($dbcon, $query);

$rows = array();
$i = 0;

while ($row = mysqli_fetch_assoc($results)) {
    $rows[] = $row;

    foreach ($rows as $row) { 
        $url = 'url'.$i;
        $$url = 'https://bla.com/tools/tracker.php?productID=' .
                $row["productname"] . '&verkoper=' . 
                $row["seller"] . '&offerid=' . 
                $row["offerid"] . '&price=' . $row["price"] . 
                '&productTracken=';

        // set URL and other appropriate options
        file_get_contents($$url);

        $i++;
    }
}

【问题讨论】:

  • 良好的代码缩进将帮助我们阅读代码,更重要的是,它将帮助您调试代码Take a quick look at a coding standard 为您自己的利益。您可能会被要求在几周/几个月内修改此代码,最后您会感谢我的。

标签: php url file-get-contents


【解决方案1】:

如果你简化你正在做的事情,你可能会得到你想要的结果

您似乎正在做的只是触摸从表格中的数据构建的 url 列表

另外,您不需要 while 循环和 foreach 循环,这肯定会导致您的问题。

$query = "SELECT distinct b.productname, b.seller, b.price, b.offerid 
          from tracker b";
$results = $dbcon->query($query);

while ($row = $results->fetch_assoc()) {

    $url = 'https://bla.com/tools/tracker.php?productID=' .
                $row["productname"] . '&verkoper=' . 
                $row["seller"] . '&offerid=' . 
                $row["offerid"] . '&price=' . $row["price"] . 
                '&productTracken=';

    // set URL and other appropriate options
    file_get_contents($url);
}

【讨论】:

  • file_get_contents() 如果启用了 fopen 包装器,则可以使用 URL。也许建议使用 cURL 作为替代方案?
  • 我是从日志站点使用日志中得到的。由于某种原因,它只访问数组中的第一个 URL。 [17/Nov/2021:17:33:02 +0100] "GET /tools/tracker.php?productID=112&verkoper=b12&offerid=123&price=6&productTracken= HTTP/ 1.0" 302 30202 "-" "-"
  • 使用此代码?或者你的原始代码。 小点你没有数组,我没有数组,这段代码一次从结果集中获取一行,并把它变成一个url
  • 使用您的代码。 302 并不重要,因为我看到该 URL 已被访问,而不是其他 URL 的..
【解决方案2】:

这里发生了一些奇怪的事情。

首先,你的循环:

while ($row = mysqli_fetch_assoc($results)) {
    $rows[] = $row;

    foreach ($rows as $row) { 

每次从数据库中获取一行时,都会将其添加到数组中。然后您立即循环遍历 该数组中的所有项目。如果你每次输出一个行号,你会得到 0;然后 0, 1;然后是 0、1、2;等等。

其次,你的 URL 变量:

$url = 'url'.$i;
$$url = 'https://...';

这使用了名为variable variables 的PHP 深奥特性:您可以动态选择所需的变量名称。这个特性基本上是从不需要的,因为使用数组几乎总是更好:

$urls[$i] = 'https://...';

不过,在这种情况下,您一次只使用一个值,因此您可以只使用一个普通的旧变量:

$url = 'https://...';

修复这些会给你RiggsFolly's answer 中的代码,并且可能会解决你的问题。

【讨论】:

    猜你喜欢
    • 2014-02-17
    • 2023-03-20
    • 2017-08-06
    • 2015-07-19
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多