Batch Results Retrieval in PHP

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

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