We have answer of your question!

100% solved queries, no empty question

Question: Use php curl to obtain return json


0

Advertisement


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.

Question author User3836484 | Source

Answer


1


Advertisement


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);
?>
Answer author U-mulder

Advertisement


Tickanswer.com is providing the only single recommended solution of the question Use php curl to obtain return json under the categories i.e php , curl , . Our team of experts filter the best solution for you.

Related Search Queries:

how to get json response using curl in php , php curl json post , php curl post json response , how to fetch data using curl in php ,

You may also add your answer!