2012-09-25 92 views
0

我正在使用cURL通過PHP來測試服務連接,並且出現了一些不一致的結果。當我運行通過PHP &捲曲的測試,這是我的結果:PHP GET請求返回不一致的結果

{"response":"\n\n\n\n \n \n 

當我把同樣的網址在瀏覽器中我得到這個:

{"response":"\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <link href=\"/images/global/global.css\...and so on 

在我的瀏覽器的響應被剪短,但你明白了。

用我的PHP,我讀了一個JSON文件,解析出我需要的URL和使用cURL發送GET請求。下面是我使用通過PHP來測試服務的代碼:

<?php 
include ("serviceURLs.php"); 

class callService { 
    function testService($url){ 

     $ch = curl_init($url); 

     curl_exec($ch); 

     $info = curl_getinfo($ch); 
     if ($info['http_code'] == 200){ 
      echo("Test has passed </br>"); 
     }else{ 
      echo("Test Failed.</br> "); 
     } 

     var_dump($info); 

     curl_close($ch); 
    } 

    function readFile(){ 
     $myFile = "./service/catalog-adaptation.json"; 
     $fr = fopen($myFile, 'r'); 
     $fileData = fread($fr, filesize($myFile)); 
     $json_a = json_decode($fileData, TRUE); 

     $prodServer = $json_a['serverRoots']['%SERVER_ROOT']['PROD']; 
     $demoServer = $json_a['serverRoots']['%SERVER_ROOT']['DEMO']; 
     $testServer = $json_a['serverRoots']['%SERVER_ROOT']['TEST']; 

     $testUrls = $json_a['commands'];  
     foreach($testUrls as $tURL){ 
      $mURL = $tURL['URL']; 

      if(stripos($mURL, "%")===0){ 
       $testTestService = str_replace("%SERVER_ROOT", $testServer, $mURL); 
       $testDemoService = str_replace("%SERVER_ROOT", $demoServer, $mURL); 
       $testProdService = str_replace("%SERVER_ROOT", $prodServer, $mURL); 

       echo ("Production test: "); 
       $this->testService($testProdService); 

       echo ("Demo test: "); 
       $this->testService($testDemoService); 

       echo ("Test test: "); 
       $this->testService($testTestService); 
      } 
     } 
    } 
} 
$newServiceTest = new callService; 
$newServiceTest->readFile(); 
?> 

誰能告訴我爲什麼我得到不同的結果,我怎麼能修復我的代碼,所以我可以得到一致的結果?

回答

3

您需要設置下面的選項,以便將返回值作爲curl_exec()的返回值的字符串返回,而不是直接輸出。

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
+0

很好的回答!謝謝!完美工作! – BlackHatSamurai