I'm trying to retrieve a result from a guzzle json post using simple php.
this is my function in file1.php EDITED this file is in a laravel 5.3 project
public function getPhotos($properties)
{
$codes = [];
foreach($properties as $property)
{
$codes[$property['codigo']] = $property['cod_filial'];
}
$client = new Client();
$response = $client->request('POST', 'http://local.app/file2.php', ['json' => \GuzzleHttp\json_encode($codes)]);
var_dump($response); exit;
}
and this is my file in a local url http://local.app/file2.php edited this file is in a project outside laravel and i have endpoint configured pointing.
<?php
$input = file_get_contents('php://input');;
$input = json_decode($input);
return $input;
Guzzle response is empty and i'm not figuring out what i'm doing wrong.
Can someone help me? Thanks a lot.
1) Try in your first file:
var_dump($response->getBody()->getContents());
// or
var_dump((string)$response->getBody());
2) Read the documentation about json option more carefully, this option accepts simple PHP array, you should not call json_encode manually.
Related
Can anyone solve this problem using GuzzleHttp? I want to display the $reportid in controller, but I'm stuck at the moment.
//Select Data For SDO Homepage Report
public function SDOHomepage(){
$client = new \GuzzleHttp\Client();
$url=WEBSERVICE_URL;
//Response 1
$response1=$client->request('POST', $url,['form_params'=>['tag'=>'selectSDOHomepage']]);
//$body = $response1->getBody();
//$reportid = $body['ReportID'];
//Response 2
$response2=$client->request('POST', $url,['form_params'=>['tag'=>'sdoCountReply','ReportID'=>$reportid]]);
$data1=json_decode($response1->getBody()->getContents(),true);
$data2=json_decode($response2->getBody()->getContents(),true);
//Return Data
return view('SDOHomepage',['SDO_All'=>$data1,'SDO_Reply_Count'=>$data2]);
}
Are you perhaps missing this?
$body = $response1->getBody();
$reportid = $body['ReportID'];
You may or may not need to do something else like json_decode.
I'm working on cakephp, make an http client where the driver is like this
public function index()
{
$http = new Client();
$response = $http->get('http://localhost/paginaws/articles/index.json');
$json = $response->json;
$valor = $response->body;
$this->set(compact(['valor']));
}
and what I want is to pass it to a view that is going to be a table. I know I have to use a foreach but it does not show me anything. When doing a var_dump shows me that it is an object type.
Before I start, I want to let you know I'm really a noob in PHP and this is the first API I'm making.
It works pretty good if I want to echo one array of information (for example food details), but when I try to do the same with multiple items it returns empty.
I've checked the variable values in debug. It's fine in debug and I see an array which contains multiple sub arrays.
My code
$app->get('/allfoods', 'authenticate', function () use ($app) {
global $user_id;
$db = new FoodHandler();
// In here i get foods with their details via mysql
$result = $db->GetAllFoods();
$response = array();
$response["error"] = false;
$response["foods"] = array();
// looping through result and preparing food array
while ($row = $result->fetch_assoc()) {
$tmp = array();
$tmp['food_id'] = $row['food_id'];
$tmp['food_name'] = $row['food_name'];
$tmp['food_desc'] = $row['food_desc'];
$tmp['food_category'] = $row['food_category'];
$tmp['food_creationDate'] = $row['food_creationDate'];
array_push($response["foods"], $tmp);
}
echoRespnse(200, $response);});
My output function (which works great if there is no array in my array)
function echoRespnse($status_code, $response) {
$app = \Slim\Slim::getInstance();
// Http response code
$app->status($status_code);
// setting response content type to json
$app->contentType('application/json');
echo json_encode($response);
}
$app->run();?>
What is my setup?
Localhost wamp with php 7.2.4
Apache 2.4.33
Mysql 5.7.21
I'm also using Postman to send my request (I also tried it in C#, both give back empty content)
I see several issues with your code. First, there is a problem with your route definition. When defining a route, you should pass two arguments to the get method: a pattern (a string,/allfoods in your case) and an instance of Clousure (a callable, your route callback, the anonymous function in your case.) More details in official docs.
So, first thing is to remove the authenticate string from method parameters and change your route definition to this:
$app->get('/allfoods', function ($request, $response, $args) {
// Body of the function goes here
});
Please note I also removed the use ($app) as you have access to application instance uising $this keyword, so no need for that (described in official docs as well).
Second thing is about generating the response. When using Slim framework it is always a good idea to return the $response object instead of echoing response (read more in official docs). Thisgives you some advantages, for example the helper method whitJson helps you whit generating JSON output.
To refine your whole code in a more Slim-ish way:
$app->get('/allfoods', function ($request, $response, $args) {
global $user_id;
$db = new FoodHandler();
// In here i get foods with their details via mysql
$result = $db->GetAllFoods();
$data= array();
$data["error"] = false;
$data["foods"] = array();
// looping through result and preparing food array
while ($row = $result->fetch_assoc()) {
$tmp = array();
$tmp['food_id'] = $row['food_id'];
$tmp['food_name'] = $row['food_name'];
$tmp['food_desc'] = $row['food_desc'];
$tmp['food_category'] = $row['food_category'];
$tmp['food_creationDate'] = $row['food_creationDate'];
array_push($data["foods"], $tmp);
}
// Return JSON data using helper method
return $response->withJson($data);
}
And you won't need the echoResponse function anymore.
I'm using Zurmo and trying to create a new account using REST API. I followed this documentation precisely: http://zurmo.org/wiki/rest-api-specification-accounts to pass the required parameters as json array.
This is my php code:
public function actionCreateOrUpdate()
{
$params=$_POST;
$modelClassName=$this->getModelName();
foreach ($params as $param)
{
if (!isset($param))
{
$message = Zurmo::t('ZurmoModule', 'Please provide data.');
throw new ApiException($message);
}
$r=$this->GetParam($param);
$res= array('status' => 'SUCCESS', 'data' => array($r));
print_r(json_encode($res,true));
}
}
function GetParam ($param){
$modelClassName=$this->getModelName();
if (isset($param['mobile_id'] ) && !$param['mobile_id']=='' &&!$param['mobile_id']==null)
{ $id=$param['mobile_id'];
$params=array();
foreach ($param as $k => $v) {
if(!($k=='mobile_id')) {
$params[$k] = $v;}
}
if ($params=null){$message = Zurmo::t('ZurmoModule', 'Please provide data.');
throw new ApiException($message);}
$tableName = $modelClassName::getTableName();
$beans = ZurmoRedBean::find($tableName, "mobile_id = '$id'");
if (count($beans) > 0)
{
$result = $this->processUpdate($id, $params);
}else{
$result = $this->processCreate($params,$id);
}
}
return $result;
}
The problem is that the $_POST method is returning an empty array. While debugging I tried to use print_r($_POST) and it also returned an empty array. I also tried to pass parameters as plain text and got the same result. I tried $_GET method and it worked. I think the problem is in the $_POST method, maybe I need to change something in my .php files. Any ideas please?
You should first hit the api with static data, to check if it works fine, then try to integrate php within that static data. You will need to read the documentation for which action accepts which format, and which method is supported(GET OR POST). Then try die(); , before sending if the array formed is as per the documentation.
I had similar issue when creating Account using REST API from java client. The problem was I did not send the proper POST request.
Another symptom also was on server side print_r(file_get_contents("php://input"),true); php code returned the correct request data.
Specifically the root cause was:
The Content-Type HTTP header was not "application/x-www-form-urlencoded"
The value field value in POST request was not properly encoded ( I used java.net.URLEncoder.encode method to overcome this)
After fixing these it worked.
I am a newbie. I am trying to make some experience about REST applications in PHP. So I receive (POST) a JSON body and store the value in my database. I just want to make a check if the JSON body I get is in the right way, if it matches the particular schema I set. I need something like this (for example):
my schema:
{"id":"int",
"name":"string",
"value":"double"
}
I just want to check that my JSON body contains the same fields and types. Thanks in advance.
UPDATE
Thanks to all for your answers. I'd like to follow krichprollsch's answer. It's exactly what I need. So I am using Ubuntu 12.04 LTS and NGINX server. I only installed HttpFoundation and Validator components via Composer. Now in my "www" folder I have a folder called "vendor" where Symfony's components are (I don't know if this folder has to be there). In order to check I made a script taken from some examples on the web but I've got a "500 Internal Server Error". The script is this:
<?php
require 'vendor/autoload.php';
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints\Lenght;
class user{
public function utente(){
$validator = Validation::createValidator();
$violations = $validator->validateValue('Bernhard', new Lenght(array('min'=>10)));
echo $violations;
}
}
$a = new user;
$a->utente();
?>
Any suggestions? Thanks
You can use the Symfony Validator component to validate the data from the json according with your schema : http://symfony.com/doc/master/book/validation.html
<?php
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;
//...
$collectionConstraint = new Assert\Collection(
array(
'id' => new Assert\Type(array('type'=>'integer')),
'name' => new Assert\Type(array('type'=>'string')),
'value' => new Assert\Type(array('type'=>'double'))
)
);
//...
$data = json_decode($your_json);
$validator = Validation::createValidator();
$errorList = $validator->validateValue($data, $collectionConstraint);
Using Symfony validator allow you to check complex constraints, not only type of data.
You can also directly validate an hydrated object. Useful if you want to insert into database.
You want chek value???
YOu can decode json strings with json_decode() function.
For example:
$json = {"id":"int",
"name":"string",
"value":"double"
};
$decode = json_decode($json);
if($decode->value == 'Your value') {
//your code
} else {
echo 'Incorerct!';
}
Hey You can decode you json by php
using json_decode function
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$array1 = json_decode($json, true);// it will return an array
for more about json_decode http://in2.php.net/json_decode
and can compare your data structure array ($array2) with this array
by intersecting them.
$result = array_intersect($array1, $array2);
print_r($result);
You can use json_decode to check if it is a valid syntax
$json = '{"id":"int",
"name":"string",
"value":"double"
}';
$decoded = json_decode($json, true);
if($decoded == null){
//your error message
echo "Error in JSON Format";
}
if the string is not valid, json_decode will return a null value