Answer the question
In order to leave comments, you need to log in
Php Phalcon how to send data in json format?
Good evening, there is such a task:
There are two sites on localhost. It is necessary to request and receive data from the second site (the first one requests). The controller action code of the first site that requests:
public function acceptAction()
{
$json = file_get_contents("php://input");
$receive_data = json_decode($json,true);
$users = $receive_data;
$this->view->users = $users;
}
public function sendAction()
{
$users = Users::find();
$send_data = json_encode($users);
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,"http://learning/test/accept");
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-type: application/json')
);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$send_data);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_HEADER,false);
curl_exec($curl);
curl_close($curl);
}
Answer the question
In order to leave comments, you need to log in
0. Make sure in /etc/hosts that the domain learning
belongs to the host 127.0.0.1
1. Check manually via the console command curl on the same server that http://learning/test/accept
returns any response
2. Check the web server
access.log logs - was there general query between two scripts
error.log - were there any errors
3. In the code sendAction()
, replace the code to see the error
if( ! $result = curl_exec($curl)) // чтобы проверить на наличие ошибки CURL или HTTP
{
trigger_error(curl_error($curl));
}
curl_close($curl);
echo $result; // чтобы видеть результат запроса
acceptAction()
, Add Code$receive_data = json_decode($json,true);
if (json_last_error()) // чтобы проверить наличие ошибки декодирования JSON
{
trigger_error(json_last_error_msg());
}
public function sendAction()
to http://learning/test/accept
in JSON format $this->view->users
class TestController
{
public function showAction()
{
$json = file_get_contents("http://learning/test/users"); // получить данные со второго сервера
$users = json_decode($json, true);
$this->view->users = $users; // передать в представление
}
}
class TestController
{
public function usersAction()
{
$users = Users::find(); // получить из базы
// подготовиться к выдаче ответа в формате JSON
$this->view->disable();
$response = new \Phalcon\Http\Response();
$response->setStatusCode(200);
$response->setJsonContent($users);
$response->setContentType('application/json', 'UTF-8');
return $response;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question