2016-07-18 8 views
-1

API와 연결을 시도하고 있습니다. 에 대한 작업을 배우고 싶습니다. 나는 문자열로 JSON 변환하려고 (나는 Laravel 작업)하지만 난 변환 된 문자열을 에코 경우는 나에게이 오류 제공 :JSON을 String으로 변환 할 수 없습니다. (PHP 및 Laravel)

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')); 
} 
: 이것은 내 HomeController.php입니다

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) 

나는 템플릿 엔진 블레이드를 사용하고, 그래서 내 에코는 다음과 같습니다

{{ $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를 사용할 필요가 없습니다. 사실 json_decode는 실제로 배열로 바뀝니다 (두 번째 매개 변수에서 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); 
} 
관련 문제