显示 PHP 中变量的值,只要它们被指定

Display the value of variables in PHP, as soon as they are specified

我想从几个不同的站点获取大约 50 个变量并将它们显示给用户,使用 PHP 简单 HTML DOM 解析器。 我的代码结构是这样的:

                    <?php


                    include('simple_html_dom.php');



                    $html = file_get_html('https://site1.com/name1/');

                        foreach ($html->find('span#name1') as $e) {
                            $name1 = $e->outertext;
                            echo $name1;
                            break;
                        }

                    $html = file_get_html('https://site2.com/family1/');

                        foreach ($html->find('span#family1') as $e) {
                            $family1 = $e->outertext;
                            echo $family1;
                            break;
                        }

                    $html = file_get_html('https://site3.com/degree1/');

                        foreach ($html->find('span#degree1') as $e) {
                            $height1 = $e->outertext;
                            echo $height1;
                            break;
                        }

                    $html = file_get_html('https://site4.com/height1/');

                        foreach ($html->find('span#height1') as $e) {
                            $height1 = $e->outertext;
                            echo $height1;
                            break;
                        }


                    // About 30 other blocks of code similar to the above code

                    ?>

目前,此代码运行良好并显示变量,但正如预期的那样,执行此过程并向用户显示所有变量大约需要两三分钟,这是很多时间。

现在我正在寻找一种方法来向用户显示(将结果发送到浏览器)找到的每个变量,然后找到下一个变量。

比如指定了$name1的值,给用户显示,然后去指定$family1

的值

显然我应该使用 flush() 来解决这个问题,但不幸的是我找不到解决这个问题的方法。

您很可能需要以略微不同的方式设计您的应用程序。一种相对简单的方法是对您需要显示的每个变量进行 AJAX 调用,并让客户端(浏览器)决定何时进行每次调用,以便您可以将它们并行化。每次呼叫都会打到一个(而且只有一个)遥控器 URL。这样,您可以在结果以 AJAX 响应形式出现时显示。

稍微复杂一点的方法是使用 Websockets 在新信息可用时发回。但我认为这可能有点矫枉过正。

在任何情况下,这两种解决方案都需要比 PHP 更多的浏览器/JavaScript 工作。

您可以使用 ob_flush 方法,例如:

<?php

include('simple_html_dom.php');

$html = file_get_html('https://site1.com/name1/');

    foreach ($html->find('span#name1') as $e) {
        $name1 = $e->outertext;
        echo $name1;
        break;
    }

    flush();
    ob_flush();

$html = file_get_html('https://site2.com/family1/');

    foreach ($html->find('span#family1') as $e) {
        $family1 = $e->outertext;
        echo $family1;
        break;
    }

    flush();
    ob_flush();

$html = file_get_html('https://site3.com/degree1/');

    foreach ($html->find('span#degree1') as $e) {
        $height1 = $e->outertext;
        echo $height1;
        break;
    }

    flush();
    ob_flush();

$html = file_get_html('https://site4.com/height1/');

    foreach ($html->find('span#height1') as $e) {
        $height1 = $e->outertext;
        echo $height1;
        break;
    }

    flush();
    ob_flush();
// About 30 other blocks of code similar to the above code

?>

此代码在每次块刷新后 PHP 输出到浏览器。