user3836484
user3836484

Reputation: 205

Use php curl to obtain return json

In file A:

<?php
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://adomain.com/test.php");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true); 
    $result = curl_exec($ch);
    var_dump(json_decode($result, true));
    curl_close($ch);
?>

In file B:

<?php
    $json['message'] = 123;
    return json_encode($json);  
?>

When run file A in browser, I expect I shall see a returned json array from file B, however I just can see it displayed "NULL". Actually what's wrong with it? thanks.

Upvotes: 0

Views: 1132

Answers (1)

u_mulder
u_mulder

Reputation: 54831

Curl takes the output of a script. So you script should output (print, echo) something:

<?php
    $json['message'] = 123;
    echo json_encode($json);  // not return
?>

If your fileA is connected with some ajax request, then you should understand the communication between client and server is performed via strings, plain simple strings.

So if fileA.php outputs something which is not a properly encoded json string, then you can't treat this output as json. And as a result cannot use output.message notation in javascript. So, your script should return properly encoded json string (which is already created by fileB):

<?php
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://adomain.com/test.php");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true); 
    $result = curl_exec($ch);
    echo $result;   // here, response from fileB which is already json
    curl_close($ch);
?>

Upvotes: 2

Related Questions