2016-07-18 3 views
-1

APIとの接続を試みていますが、 で操作する方法を知りたいです。 (私はLaravelで動作する)私は 文字列にJSONに変換しようとしていますが、私はそれは私に、このエラーを与える変換後の文字列エコー場合:JSONを文字列に変換できません(PHPおよびLaravel)

ErrorException in helpers.php line 531: 
htmlentities() expects parameter 1 to be string, array given (View: /home/stackingcoder/development/PHP/internetstuffer/resources/views/index.blade.php) 

をこれが私のHomeController.phpです:

public function index() 
{ 
    $url = 'https://www.quandl.com/api/v3/databases/WIKI.json'; 
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $data = curl_exec($ch); 
    $string = json_decode($data, true); 

    curl_close($ch); 

    return view('index', compact('string')); 
} 

私はテンプレートエンジンのブレードを使用していますので、私のエコーは次のようになります。

{{ $string }} 

編集:

最終的には配列が必要ですが、APIコールを配列に変換するにはどうすればよいですか?したがって、このようなデータを分割することができますで:

echo $data['database']['name']; 

答えて

0

は自分の最後の行を変更します。 json_decodetrueフラグを指定すると、配列が返されます。

public function index() 
{ 
    $url = 'https://www.quandl.com/api/v3/databases/WIKI.json'; 
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $data = curl_exec($ch); 
    $string = json_decode($data, true); 

    curl_close($ch); 

    // name can be called here as $string['database']['name'] 

    // once passed the string to view, called inside blade as $database['name'] 
    // It seems i have to use compact, otherwise it will give me the 
    // error: Undifined variable: $string 
    return view('index', compact('string')); 
} 
0

それはview機能が何であるか、あなたのサンプルからかなり明確ではないですし、それが定義されますが、どのような場合には、あなたの文字列にcompactを実行するので、あなたはおそらく摂食されていますあなたのテンプレートシステムのある部分は、文字列を期待する配列です。

PHP docs:compact - >変数とその値を含む配列を作成します。

0

JSONを文字列として使用する場合は、cURLによって返されるときはすでに文字列です。 json_decodeは、実際には配列に変換されます(2番目のパラメータでtrueに設定されているので)。

コンパクト関数でも配列が作成されるため、これも取り上げています。 (参照:http://php.net/manual/en/function.compact.php)を

public function index() 
{ 
    $url = 'https://www.quandl.com/api/v3/databases/WIKI.json'; 
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $data = curl_exec($ch);  
    curl_close($ch); 

    return view('index', $data); 
} 
関連する問題