2015-10-07 2 views
0

Я получаю адресные координаты с адресов. Пользователь может загрузить файл CSV, который имеет 100 или 1000 записей, и после этого я выборки данных координат с использованиемПоказать индикатор выполнения при выполнении php multiple curl

$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']; 

Я хочу обновить прогресс бар, когда каждая запись извлекается.

Например, предположим, что у меня есть 100 записей в CSV. Каждый раз, когда я получаю координаты, я хочу увеличить индикатор выполнения. Другими словами, я хочу, чтобы пользователь мог видеть, сколько координат было успешно выбрано.

Я следую примеру 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 <[email protected]>" . $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

+0

«Как я могу это сделать?» это не вопрос, на который мы можем ответить. Вы делаете это, написав соответствующий код. Перепишите свой пост. –

+0

Хорошо. Пожалуйста, дайте мне немного времени. После этого я обновлю свой вопрос. –

+0

Я обновил свой вопрос. Пожалуйста, проверьте сейчас. –

ответ

0

Как это вы не можете показать прогресс бар ... Когда вы отправите form post отправляется на php, который запускает ваш код только на сервере, и только когда он заканчивает запуск, он отправляет содержимое html обратно в ваш браузер.

Итак ... этот сценарий php не может вести себя так, как вы хотите.

Одна вещь, которую вы могли бы попробовать, если точный прогресс в том, что важно ...

Вы можете отправить форму с помощью AJAX для PHP скрипт (на сервере).

PHP-скрипт прочитает весь CSV-файл и отправит его обратно в json-массив вызывающему js на клиенте (ваш браузер).

js проанализирует массив «по строкам», и для каждой строки он отправит один запрос ajax другому скрипту php, который сохранит эту единственную запись и воспроизведет «ok» (сервер).

звонившего скрипт расслоение плотной (браузер) будет обновлять индикатор прогресса и сделать еще один вызов ...

продолжать делать это недо конец массива.

Смежные вопросы