顯示具有 php 標籤的文章。 顯示所有文章
顯示具有 php 標籤的文章。 顯示所有文章

2015年11月9日 星期一

Google問卷根據地址自動查詢3+2郵遞區號

因為最近在準備結婚的事,使用了google form來統計賓客資料。用google apps script寫了一個小程式(參考https://gist.github.com/mhawksey/1442370),透過http://tools.5432.tw/zip5api.html提供的API自動查詢3+2碼郵遞區號。分享給大家。

由於API作者有提到不要連續查詢,最好間隔一秒,因此請不要更動code內部sleep的部分。否則會被API作者封鎖來源網址。作者已經將google script的來源封鎖,這讓我在一開始的時候花了不少功夫debug。所以使用者必須提供一個web server供redirect來源繞過封鎖。

google apps script

function onOpen() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [{
    name : "fix郵遞區號",
    functionName : "findpostcode"
  }];
  spreadsheet.addMenu("fix郵遞區號", entries);
};

/**
 * Runs when the add-on is installed; calls onOpen() to ensure menu creation and
 * any other initializion work is done immediately.
 *
 * @param {Object} e The event parameter for a simple onInstall trigger.
 */
function onInstall(e) {
  onOpen(e);
}

/**
 * Opens a sidebar. The sidebar structure is described in the Sidebar.html
 * project file.
 */
function findpostcode() {
  var o = 4; //4為修正前地址的欄位,可依需求修正
  var a = 14; //將修正後之地址輸出到第14欄,可依需求修正
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Form Responses 1");
  var TIDrange = sheet.getRange(1,1,sheet.getMaxRows(), a);
  var rows = sheet.getLastRow();

for (i = 2; i <= rows; i++)
  {
      var dirtyaddress = TIDrange.getCell(i,o).getValue().toString().replace(/ /g,"");
 
      var address = dirtyaddress.split(/^[0-9]*/)[1]; //去除已填寫之郵遞區號(可能為3碼)
   
      var target = TIDrange.getCell(i,a).getValue().toString().replace(/ /g,"");
 
    if (target == "") {
      if (typeof address === 'undefined') {address = dirtyaddress;}
   
      var response = UrlFetchApp.fetch("這邊放入轉址的網站"+address)
      Utilities.sleep(1000); //此行勿動
      var dataAll = JSON.parse(response.getContentText());
   
      var newaddr = dataAll.new_adrs;
   
      sheet.getRange(i,a).setValue(newaddr);
   
    }
  }

webserver PHP

<?php

if (isset($_GET['link'])) {
//    echo $_GET['link'];

echo file_get_contents($_GET['link']);

}else{
   // Fallback behaviour goes here
}

?>

由於API使用url參數會自動decode % encode,所以一開始遇到一點麻煩,後來發現我不用去store資料,只要直接echo就OK。

將webserver PHP放在webserver如apache下,假設檔名為phpexample.php,domain name為neverregret.net,則google apps script紅字部分這邊放入轉址的網站

http://neverregret.net/phpexample.php?link=http://zip5.5432.tw/zip5json.py?adrs=

將google apps script部分複製並貼在工具-指令碼編輯器的內容(將內容先全部清空)

儲存後工具列會出現fix郵遞區號的選項,點選後執行即可使用。

查詢流程為如果尚未修正則修正(修正欄位不為空白),已修正則不處理,所以如果地址有變要記得將修正後欄位也一併清除。這樣做是為了不用每次都全部重新修正。

如有親友想使用請直接與我聯繫,我可以提供我自己的webserver供使用。

參考資料
API
http://tools.5432.tw/zip5api.html

unicode decode encode (didn't use in the end)
http://www.cnblogs.com/txw1958/archive/2013/04/20/unicode-encode-decode.html
http://stackoverflow.com/questions/16943281/javascript-google-scripts-how-to-get-the-title-of-a-page-encoded-with-iso-88
http://stackoverflow.com/questions/332872/encode-url-in-javascript
http://stackoverflow.com/questions/23496750/how-to-prevent-python-requests-from-percent-encoding-my-urls
http://blog.bestdaylong.com/2010/09/phputf8get.html
http://www.ewdna.com/2008/12/online-urlencoderutf-8.html
http://stackoverflow.com/questions/17342671/pass-a-percent-sign-in-a-url-and-get-exact-value-of-it-using-php
http://blog.lunatech.com/2009/02/03/what-every-web-developer-must-know-about-url-encoding

PHP
http://stackoverflow.com/questions/5884807/get-url-parameter-in-php
http://stackoverflow.com/questions/959063/how-to-send-a-get-request-from-php
determine undefine
http://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null


JSON array
http://stackoverflow.com/questions/14408281/access-elements-in-json-object-like-an-array
javascript split
http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript

google apps script
https://gist.github.com/mhawksey/1442370
http://ctrlq.org/code/19871-get-post-requests-google-script
https://developers.google.com/apps-script/guides/html/
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#getRequest(String,Object)
https://discuss.ninjablocks.com/t/google-script-for-parsing-json-to-google-spreadsheets/1088/4
https://developers.google.com/apps-script/reference/spreadsheet/range
http://stackoverflow.com/questions/11334296/google-docs-script-set-cell-value

google spreadsheet
https://support.google.com/docs/answer/3093335?hl=zh-Hant

javascript
http://stackoverflow.com/questions/2499567/how-to-make-a-json-call-to-a-url/2499647#2499647
http://stackoverflow.com/questions/18910939/how-to-get-json-key-and-value-in-javascript
http://stackoverflow.com/questions/12070631/how-to-use-json-file-in-html-code

JSON test site
http://developers.squarespace.com/view-json-data/
http://base-template.squarespace.com/blog/?format=json-pretty

2015年8月10日 星期一

apache php 接收 json

關鍵在apache的目錄必須開啟apache user讀寫權限。另外我遇到的狀況是傳送整個json檔案,因此必須使用json_decode函式將json file轉換成array才能進一步使用。
<?php
//header("Content-Type: application/json", true);

$filename = fopen('test.json', 'w');  //打開json暫存檔,'w'參數為每次打開皆清空檔案

if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){ 
    $postText = file_get_contents('php://input'); 


fwrite($filename, $postText);  //寫入暫存檔
fclose($filename);  //關閉暫存檔

$url = "http://target.php";  //改成需要轉發的url

$data_decode = json_decode($postText);  //json格式解碼
$data_string = json_encode($data_decode);  //json格式編碼,這邊的目的是再將收到的json轉發出去                                                                                 
                                                                                                                     
$ch = curl_init($url);                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   
                                                                                                                     
$result = curl_exec($ch);


}

?>

上面的範例是當對方發送json過來時,將收到的json file再轉發到另一個url的webserver。
另外jquery必須將.js嵌入網頁,可由網路或本地端,之後才可以使用。

清除舊的ubuntu repository資料
sudo sed -i -e 's/archive.ubuntu.com\|security.ubuntu.com/old-releases.ubuntu.com/g' /etc/apt/sources.list
sudo apt-get update

參考資料

php curl post

http://stackoverflow.com/questions/15200632/how-to-upload-file-using-curl-with-php
http://askubuntu.com/questions/9293/how-do-i-install-curl-in-php5
https://www.digitalocean.com/community/questions/installing-curl-on-ubuntu-12-04
http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/
http://reader.roodo.com/esabear/archives/16358749.html
http://blog.roodo.com/esabear/archives/16358749.html
http://stackoverflow.com/questions/19758954/get-data-from-json-file-with-php
http://markonphp.com/php-curl-basic-post-example/
http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl

php receive post

http://stackoverflow.com/questions/938811/receive-xml-file-via-post-in-php
http://stackoverflow.com/questions/19004783/reading-json-post-using-php
http://stackoverflow.com/questions/15220704/how-to-detect-if-post-is-set
http://www.blog.magepsycho.com/sending-json-data-remote-server/
http://www.php.net/manual/en/function.json-decode.php
http://codex.wiki/post/166087-764/
http://josh.gourneau.com/blog/2010/11/16/serve-json-as-content-type-applicationjson-with-apache-on-ubuntu/
https://blog-ldkrsi.rhcloud.com/php%E6%8E%A5%E6%94%B6post%E4%BE%86%E7%9A%84json%E8%B3%87%E6%96%99/
http://www.j2h.tw/bbs/bbs16/519.html
http://phpwolf.blogspot.tw/2013/08/php-post-json.html
http://stackoverflow.com/questions/18866571/receive-json-post-with-php

POST測試

https://www.hurl.it/

jquery傳送資料給php,php再回傳

https://docs.google.com/document/d/1U0n01CVFllcpd5Irzk8999x8ALHck5M4vOJizA_mYvs/pub
http://italwaysrainonme.blogspot.tw/2013/02/jqueryjsonphp-phpjsonjquery.html
http://kinomelma.pixnet.net/blog/post/30403239-%5B%E8%B6%85%E7%B0%A1%E6%98%93%5D-jquery-json-%E6%A0%BC%E5%BC%8F%E6%8E%A5%E6%94%B6%E8%88%87%E5%88%86%E6%9E%90

android溝通

http://j796160836.pixnet.net/blog/post/28994669-%5Bandroid%5D-%E4%BD%BF%E7%94%A8http%E7%9A%84post%E6%96%B9%E5%BC%8F%E5%92%8C%E7%B6%B2%E9%A0%81%E8%A1%A8%E5%96%AE%E6%BA%9D%E9%80%9A

install jquery

http://stackoverflow.com/questions/1458349/installing-jquery
http://www.mkyong.com/jquery/jquery-html-example/
https://developers.google.com/speed/libraries/#jquery
http://www.mkyong.com/jquery/jquery-hello-world/
http://expect7.pixnet.net/blog/post/37919326-%5B%E7%A8%8B%E5%BC%8F%5D%5Bjquery%5D-jquery%E4%B8%AD%E7%9A%84ajax%E7%9A%84%E5%9F%BA%E7%A4%8E%E9%81%8B%E7%94%A8%E3%80%82%E6%8F%90%E4%BE%9B%E7%AF%84
http://blog.jex.tw/blog/2013/02/19/php-json/
http://www.mkyong.com/jquery/jquery-html-example/

php server上傳

http://givemepass.blogspot.tw/2013/06/php-server.html

php fwrite example

http://php.net/manual/en/function.fwrite.php

2015年2月3日 星期二

selenium download file, php

Download File [Arguments] ${COOKIE} ${URL} ${FILENAME} ${COOKIE_VALUE} = Call Selenium API get_cookie_by_name ${COOKIE} Run and Return RC wget --cookies=on --header "Cookie: ${COOKIE}=${COOKIE_VALUE}" -O ${OUTPUT_DIR}${/}${FILENAME} ${URL}

php POST變數.$_POST["item"]後方如果要接字必須以 "," or "." 隔開,否則會出錯

fopen file時在linux下會有權限問題,要注意需給予使用者read權限否則會無法讀取。

使用fgets取得txt資料時,會帶出行尾的特殊符號,以windows為例為\r\n。因此在做比對時,不論是使用==或strcmp()函數都需要先將這些特殊符號消去(或是在輸入端增加),才能成功比對。

我是使用ereg_replace("\r\n","",變數)來做。供參考。順帶一提,如果將\0消去則整個字串會消失。

想要驗證則可以使用strlen()函數來觀察字串的長度,就可以知道其實有特殊符號的存在。

最後apache的預設使用者是www-data(可去/etc/apache2/envvar修改),如果要使用fopen讀取檔案記得將www-data加到owner群組內,virtualbox shared folder共用資料夾則是要將www-data加到vboxsf群組內才可正常讀取。

#sudo gpasswd -a www-data vboxsf

#sudo usermod -G vboxsf www-data 有一樣效果

以下code可以查看group內成員
$ sudo grep ^群組名稱: /etc/group

過程中由於出錯使得apache內的log資料量暴增,一開始不知道只覺得硬碟空間怎麼消失這麼快,後來使用指令列出資料夾大小才找出來。max-depth是指只顯示一層,-B M是以MB表示,sort -g是照大小排列。

du -B M --max-depth=1 | sort -g

參考資料
自己經驗
https://blog.codecentric.de/en/2010/07/file-downloads-with-selenium-mission-impossible/
http://php.net/manual/en/function.shell-exec.php
http://stackoverflow.com/questions/2404794/strcmp-on-a-line-read-with-fgets
將ubuntu內資料夾所佔空間列出
http://banco.pixnet.net/blog/post/21967119-%5Bubuntu%5D-%E5%88%A9%E7%94%A8du%E6%90%AD%E9%85%8Dsort%E4%BE%86%E6%9F%A5%E7%9C%8B%E7%A3%81%E7%A2%9F%E4%BD%BF%E7%94%A8%E7%A9%BA%E9%96%93
fget
http://qaautomationworld.blogspot.in/2014/02/file-downlaoding-using-selenium.html
http://stackoverflow.com/questions/7618155/how-to-duplicate-a-request-using-wget-or-curl-with-raw-headers
https://addons.mozilla.org/zh-TW/firefox/addon/export-cookies/
http://stackoverflow.com/questions/4272770/wget-with-authentication