A
A
Angelxalfa2015-04-05 20:49:21
PHP
Angelxalfa, 2015-04-05 20:49:21

Returning cURL data as an array?

Hello!
There are two scripts, on different servers.
Script1 sends post data to Script2 via cURL. That according to these data receives the data from a database.
How to make it send the data received from the database to Script1 as an array, so that later Script1 can operate on them? Because it passes them as a string. Or how then to turn the resulting string into an array?
script 1

if( $curl = curl_init() ) {
    curl_setopt($curl, CURLOPT_URL, 'http://11.11.11.11/table_query_order.php');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, "select=street&table=table&order=street");
    $out = curl_exec($curl);
    curl_close($curl);
  }
  echo $out;

Script2
if (!$dbconn) {
      echo "Произошла ошибка подключения к базе.";
    }
    $prefix = 'kjhhl_';
    $select = $_POST['select'];
    $table = $_POST['table'];
    $order = $_POST['order'];
  $table_query = pg_query($dbconn, "select $select from ".$prefix."$table ORDER BY $order");
    if (!$table_query) {
      echo "Произошла ошибка";
    }
      $arr = pg_fetch_all ($table_query);
  var_export($arr);

Result:
array ( 0 => array ( 'street' => 'st1', ), 1 => array ( 'street' => 'st2', ), 2 => array ( 'street' => 'st3', ), etc....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yaroshevich, 2015-04-05
@Angelxalfa

You need data serialization and deserialization.
Serialize+unserialize
json_encode+json_decode
etc.
So in script 1 instead of `echo $out` you do `json_decode($out);`.
And in script 2 instead of `var_export($arr);` you do `echo json_encode($arr);`.
Don't forget to wrap the error messages in script 2 in the same json so that you can do less bodywork in script 1. Those. make script 2 always return json.
That is, instead of:

if (!$dbconn) {
  echo "Произошла ошибка подключения к базе.";
}

Need
if (!$dbconn) {
  echo json_encode(["error" => "Произошла ошибка подключения к базе."]);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question