Batch Results Retrieval in PHP

From Textserver wiki
Revision as of 12:32, 21 January 2016 by Padro (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
 1 #! /usr/bin/php5
 2 
 3 <?php
 4 
 5 //////////////////////////////////////////////////////////////////
 6 //
 7 // Example client to retrieve the results of a batch request to TextServer  
 8 //
 9 //  Output will be a ZIP file containing results for each input file in
10 // the requested format (XML, json, conll)
11 //
12 /////////////////////////////////////////////////////////////////
13   
14   echo 'TextServer Username: '; $user = rtrim(fgets(STDIN));
15   echo 'TextServer Job Token ID: '; $tkid = rtrim(fgets(STDIN));
16   echo 'Output ZIP file: '; $outfile = rtrim(fgets(STDIN));
17 
18   // build request
19   $TextServer_URL="http://frodo.lsi.upc.edu:8080/TextWS/textservlet/ws";
20 
21   // prepare request to poll for completion and retrieve results
22   $h = curl_init();
23   curl_setopt($h, CURLOPT_URL, $TextServer_URL."/resultRetrieve"); 
24   curl_setopt($h, CURLOPT_POST, true);
25   curl_setopt($h, CURLOPT_POSTFIELDS, array(
26                                        'username' => $user,
27                                        'tokenID' => $tkid,
28                                       ) );
29   curl_setopt($h, CURLOPT_HEADER, false);
30   curl_setopt($h, CURLOPT_RETURNTRANSFER, 1);
31 
32   // execute request   
33   $result = curl_exec($h);
34   // get status
35   $err = curl_getinfo($h, CURLINFO_HTTP_CODE);
36   // close connection
37   curl_close($h);
38 
39   if ($err == 503 and strpos($result, '[TS-125]')!==FALSE) {
40     // http status 503, textserver code TS-125 means the job is not finished yet.
41     print "Job not finished yet\n";
42     exit(0);
43   }
44   else if ($err !== 200) {
45     // some other unexpected error happened. Report it
46     print "HTTP ".$err." - ".$result."\n";
47     exit(1);
48   }
49 
50   // response is ok, the job is done and we got the results. 
51   // write results to output ZIP file.
52   $outf = fopen($outfile, "wb");
53   fwrite($outf, $result);
54   fclose($outf);
55   print "Job finished. Results saved to ".$outfile."\n";
56  
57 ?>