执行php多个curl时显示进度条

时间:2015-10-07 16:38:52

标签: php csv curl

我从地址获取地址坐标。用户可以上传包含100或1000条记录的CSV文件,之后我将使用

获取坐标数据
$cityclean   = str_replace(" ", "+", $address);
$details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=false";
$ch          = curl_init();
curl_setopt($ch, CURLOPT_URL, $details_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$geoloc = json_decode(curl_exec($ch), true);
$lat    = $geoloc['results'][0]['geometry']['location']['lat'];
$lng    = $geoloc['results'][0]['geometry']['location']['lng'];

我想在获取每条记录时更新进度条。

例如,假设我在CSV中有100条记录。每当我得到坐标时,我想增加进度条。 换句话说,我希望用户能够看到已经成功获取了多少个坐标。

我正在关注示例here,但它无法正常工作。进度条未运行。

这是我的完整代码:

    <table >
    <form action="<?php
    echo $_SERVER["PHP_SELF"];
    ?>" method="post" enctype="multipart/form-data">

    <tr>
    <td width="20%">Select file</td>
    <td width="80%"><input type="file" name="file" id="file" /></td>
    </tr>

    <tr>
    <td width="20%">Or Enter Address:</td>
    <td width="80%"><input type="text" name="address" id="address" /></td>
    </tr>


    <tr>
    <td width="20%">Email address to send geo-Locationfile:</td>
    <td width="80%"><input type="text" name="email" id="email" /></td>
    </tr>

    <tr>
    <td></td>
    <td><input type="submit" name="submit" /></td>
    </tr>

    </form>
    </table>
    <h2>NOTES:</h2>
     1.)You can fetch only 10 rows from CSV file, Because this is a demo.
     <br>
     2.)If you provide address, Then you are not able to download or email generated geoCode file .
     <br><br><br><br><br><br>
     <h2>Results:-</h2>
    <br>
    <?php
    if (isset($_POST["submit"])) {
require_once 'class.ProgressBar.php';
echo '<div style="width: 300px;">';
 //$p->render();
 echo '</div>';
    if (isset($_FILES["file"])) {

    //if there was an error uploading the file
    if ($_FILES["file"]["error"] > 0) {
        //echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        $data = $_POST["address"];

        $address = trim($data);
        if ($address != "") {
            $cityclean   = str_replace(" ", "+", $address);
            $details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=false";
            $ch          = curl_init();
            curl_setopt($ch, CURLOPT_URL, $details_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $geoloc = json_decode(curl_exec($ch), true);
            $lat    = $geoloc['results'][0]['geometry']['location']['lat'];
            $lng    = $geoloc['results'][0]['geometry']['location']['lng'];
            echo $address . "------Latitude:      " . $lat . "  ----  Longitude: " . $lng;
        } else {
            echo "Please enter a address, Or upload a CSV file.";
        }

    } else {
        //Print file details
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        $name    = $_FILES['file']['name'];
        $ext     = strtolower(end(explode('.', $_FILES['file']['name'])));
        $type    = $_FILES['file']['type'];
        $tmpName = $_FILES['file']['tmp_name'];

        // check the file is a csv
        if ($ext === 'csv') {
            if (($handle = fopen($tmpName, 'r')) !== FALSE) {
                // necessary if a large csv file
                set_time_limit(0);
                $row  = 1;
                $file = fopen('ids.txt', 'w');
               $num_records =sizeof(fgetcsv($handle, 1000, ','));
              // $calc = 100/$num_records;
                $calc=100/20;
                $x=1;
                $p = new ProgressBar();
                $p->render();
                while ((($data = fgetcsv($handle, 1000, ',')) !== FALSE) && $row != 20) {
                    // number of fields in the csv
                    $address     = implode(",", $data);
                     $p->setProgressBarProgress($x); 
                    $cityclean   = str_replace(" ", "+", $address);
                    $details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=false";
                    $ch  = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $details_url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    $geoloc = json_decode(curl_exec($ch), true);
                    $lat    = $geoloc['results'][0]['geometry']['location']['lat'];
                    $lng    = $geoloc['results'][0]['geometry']['location']['lng'];
                  //  echo $address . "------Latitude:      " . $lat . "  ----  Longitude: " . $lng;
                    fwrite($file, $address . "------Latitude:      " . $lat . "  ----  Longitude: " . $lng . "\n");


                   // echo "<br/>";
                   // echo $details_url;
                    //show progress bar
                    echo $x;echo "<br/>";
                    $x += $calc;
                    //$x++;
                    $row++;
                }
                fclose($file);
                fclose($handle);

                echo "\n To download generated file <a href='ids.txt'>Click Here</a> . \n";
               /* $file      = "ids.txt";
                $email2    = $_POST["email"];
                $file_size = filesize($file);
                $handle    = fopen($file, "r");
                $content   = fread($handle, $file_size);
                fclose($handle);
                $filename = "geoCode.txt";
                $content  = chunk_split(base64_encode($content));

                // a random hash will be necessary to send mixed content
                $separator = md5(time());

                $message = "Please find your geo location file as an attachment.";

                // carriage return type (we use a PHP end of line constant)
                $eol = PHP_EOL;

                // main header (multipart mandatory)
                $headers = "From: name <test@test.com>" . $eol;
                $headers .= "MIME-Version: 1.0" . $eol;
                $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol;
                $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
                $headers .= "This is a MIME encoded message." . $eol . $eol;

                // message
                $headers .= "--" . $separator . $eol;
                $headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
                $headers .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
                $headers .= $message . $eol . $eol;

                // attachment
                $headers .= "--" . $separator . $eol;
                $headers .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
                $headers .= "Content-Transfer-Encoding: base64" . $eol;
                $headers .= "Content-Disposition: attachment" . $eol . $eol;
                $headers .= $content . $eol . $eol;
                $headers .= "--" . $separator . "--";

                //SEND Mail
                if (mail($email2, "geoCode", "", $headers)) {
                    echo "mail send to " . $email2 . " ... OK"; // or use booleans here
                } else {
                    echo "mail send ... ERROR!";
                }*/

            }

        }
    }
} else {

}
    }

    ?>

以下是CSV的链接:

https://drive.google.com/open?id=0Bx3FBqTEy_0MaHp1QVhiNkVTLU0

1 个答案:

答案 0 :(得分:0)

就像你不能显示进度条...当你提交表单时,帖子被发送到php,它只在服务器上运行你的代码,只有当它完成运行时才会将html内容发送回你的浏览器。

所以......这个php脚本无法按照你的意愿行事。

如果准确的进展很重要,你可以尝试一件事......

您可以通过ajax将表单提交到php脚本(在服务器中)。

php脚本将读取整个csv文件并将其以json数组发送回客户端(您的浏览器)上的调用者js。

js将逐行解析数组,并且对于每一行,它将向另一个php脚本发送单个ajax请求,该脚本将存储该单个记录并重放“ok”(服务器)。

调用者js脚本(浏览器)将更新进度条并再次进行一次调用...

继续这样做,直到数组结束。