2015-04-23 94 views
1

我正試圖通過curl與兩個zf2應用程序建立通信。所需響應在xml中。到目前爲止,我可以建立連接,並返回xml作爲響應。在ZF2中實現捲曲

問題

的問題是,我不能在我的xml response。每當我遍歷和的var_dump我$response->getContent的視圖源代碼,我得到儘可能

string(142) "<?xml version="1.0" encoding="UTF-8"?> 
<myxml> 
<login> 
<status>success</status> 
<Err>None</Err> 
</login> 
</myxml> 
" 

,當我只需var_dump我的$response,我得到一個object(Zend\Http\Response)#440

simplexml_load_string($response->getContent())給了我一個空白頁。

另外print $data->asXML()給我Call to a member function asXML() on a non-object錯誤。我在這裏做錯了什麼?

捲曲請求動作

$request = new \Zend\Http\Request(); 
    $request->getHeaders()->addHeaders([ 
     'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8' 
    ]); 
    $request->setUri('http://localhost/app1/myaction'); 
    $request->setMethod('POST'); //uncomment this if the POST is used 
    $request->getPost()->set('curl', 'true'); 
    $request->getPost()->set('email', '[email protected]'); 
    $request->getPost()->set('password', '2014'); 

    $client = new Client; 
    $client->setAdapter("Zend\Http\Client\Adapter\Curl"); 

    $response = $client->dispatch($request); 

    var_dump($response);//exit; 
    //$response = simplexml_load_string($response->getContent()); 
    //echo $response;exit; 
    return $response; 

捲曲響應行動

  $php_array=array(
     'login'=>array(
     'status'=>'failed','Err'=>'Unauthorised Access' 
     ) 
     ); 
     $Array2XML=new \xmlconverter\Arraytoxml; 
     $xml = $Array2XML->createXML('myxml', $php_array); 
     $xml = $xml->saveXML(); 
     //echo $xml;exit; 
      $response = new \Zend\Http\Response(); 
      $response->getHeaders()->addHeaderLine('Content-Type', 'text/xml; charset=utf-8'); 
      $response->setContent($xml); 
      return $response; 

Array2XML可以發現here

任何想法?

+1

simplexml_load_string返回一個對象SimpleXMLElement – Hooli

+3

如果你得到一個空白頁面,你有關閉顯示錯誤(這是ZF默認值)。檢查Web服務器錯誤日誌以查看實際錯誤。 –

+0

您是否嘗試過使用原始CURL而不是zf2適配器? – Conti

回答

1

時,我只是我的var_dump $迴應,我得到一個對象(Zend的\ HTTP \響應)#440

這是正確的,它會告訴你的$response類型。

simplexml_load_string($ response-> getContent())給了我一個空白頁。

這是正確的,因爲儘管此函數可以返回一個可表達爲空字符串的值,但它不會自行創建任何輸出,因此預期會出現空白頁。

任何想法?

首先,你應該制定一個適當的問題陳述與你的問題。你所期望的所有內容都是可以預料的,所以你的問題至多不清楚。

其次,你需要做適當的錯誤處理,並做一些安全的編程:

$buffer = $response->getContent(); 
if (!is_string($buffer) || !strlen($buffer) || $buffer[0] !== '<') { 
    throw new RuntimeException('Need XML string, got %s', var_export($buffer, 1)); 
} 
$xml = simplexml_load_string($buffer); 
if (false === $xml) { 
    throw new RuntimeException('Unable to parse response string as XML'); 
} 

那就是:對於你每一個參數,驗證它。對於您收到的每個功能或方法結果,請檢查後續條件。在調用函數或方法之前,請檢查每個參數的前提條件。

將錯誤記錄到文件並處理未捕獲的異常。

作爲一個附加想法:將數組的使用放到XML函數中,並將其替換爲維護的庫。在你的情況下,使用你自己的SimpleXML來創建XML可能更容易。