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
Related
I'm new to Google Vision API Client Lib
I'm using Vision API Client Lib for PHP to detect text in images, this is my code:
<?php
require 'vendor/autoload.php';
use Google\Cloud\Vision\VisionClient;
function object_to_array($object) {
return (array) $object;
}
$vision = new VisionClient(
['keyFile' => json_decode(file_get_contents("smartcity-credentials.json"), true)]
);
$img = file_get_contents('img2.jpg');
$image=$vision->image($img,['DOCUMENT_TEXT_DETECTION']);
$result=$vision->annotate($image);
$res=object_to_array($result);
var_dump($res);
?>
All I need is using response as an array for handling, but $result returns something likes array of object/object ( sorry because I don't know much of OOP/Object)
Although i convert $result to array $res, but if I use foreach loop
foreach ($res as $key=>$value){
echo $value;
echo '<br>';
}
I get this
Catchable fatal error: Object of class Google\Cloud\Vision\Annotation\Document could not be converted to string
How do we get value (text detected) in above response for using ?.
You should use the methods fullText() and text() in order to access to the detected text, something like this:
$document = $annotation->fullText();
$text = $document->text();
See the specification of these classes Annotation and Document.
you cannot use $value of type Document as string with the echo.
use print_r($annotation); to see what you even get returned.
this document text detection example looks quite alike, notice the nested foreach loops there. also see the documentation:
use Google\Cloud\Vision\VisionClient;
$vision = new VisionClient();
$imageResource = fopen(__DIR__.'/assets/the-constitution.jpg', 'r');
$image = $vision->image($imageResource, ['DOCUMENT_TEXT_DETECTION']);
$annotation = $vision->annotate($image);
$document = $annotation->fullText();
$info = $document->info();
$pages = $document->pages();
$text = $document->text();
here's some more examples; in particular the detect_document_text.php.
I need help to properly use json_encode() to return a JSON representation of a value in my php server script. As far as i learned, this is not done with echo, print or loop as explained in all the other questions i studied before asking.
How do i get one "Value" from my data.json file
{
"clientPrivateKey": {
"Name":"AWS_CLIENT_SECRET_KEY",
"Value":"someexammplestring"
},
"serverPublicKey": {
"Name":"AWS_SERVER_PUBLIC_KEY",
"Value":"someexammplestring"
},
"serverPrivateKey": {
"Name":"AWS_SERVER_PRIVATE_KEY",
"Value":"someexammplestring"
},
"expectedBucketName": {
"Name":"S3_BUCKET_NAME",
"Value":"someexammplestring"
}
}
into the corresponding PHP variable in my php server script?
$clientPrivateKey =
$serverPublicKey =
$serverPrivateKey =
$expectedBucketName =
I only need the "Value" string here. The value is supposed to give a valid JSON response inside the php server script calculating signatures or else it will {"invalid":true}. Thanx for your help!
To get the data from a JSON file, you use json_decode(), not json_encode(). Then you access the parts of it using normal PHP object syntax.
$json = file_get_contents("data.json");
$data = json_decode($json);
$clientPrivateKey = $data->clientPrivateKey->Value;
$serverPublicKey = $data->serverPublicKey->Value;
$serverPrivateKey = $data->serverPrivateKey->Value;
$expectedBucketName = $data->expectedBucketName->Value;
1. You need to decode your JSON to make it usable:
$json = json_decode($jsonString, true);
Note the second parameter set to 'true', it means that we want an associative array instead of an object.
2. You can now use your JSON as a regular associative array:
$clientPrivateKey = $json['clientPrivateKey']['Value'];
You can access the two others values you want by following the previous example.
If you want to know if the offset is valid you can use the isset() function on it.
You need to use json_decode() like so:
$json = json_decode({
"clientPrivateKey": {
"Name":"AWS_CLIENT_SECRET_KEY",
"Value":"someexammplestring"
},
"serverPublicKey": {
"Name":"AWS_SERVER_PUBLIC_KEY",
"Value":"someexammplestring"
},
"serverPrivateKey": {
"Name":"AWS_SERVER_PRIVATE_KEY",
"Value":"someexammplestring"
},
"expectedBucketName": {
"Name":"S3_BUCKET_NAME",
"Value":"someexammplestring"
}
},true);
$clientPrivateKey = $json['clientPrivateKey']['Value'];
$serverPublicKey = $json['serverPublicKey']['Value'];
$serverPrivateKey = $json['serverPrivateKey']['Value'];
$expectedBucketName = $json['expectedBucketName']['Value'];
There you go:
<?php
$json = json_decode(file_get_contents('data.json'));
$clientPrivateKey = $json->clientPrivateKey->Value;
// ...
You can use this one liner to code to automatically extract the variables from an array:
extract(array_combine(array_keys($array=json_decode($json,true)),array_column($array,"Value")));
// $clientPrivateKey,$serverPublicKey,$serverPrivateKey,$expectedBucketName are now set
Example: http://sandbox.onlinephpfunctions.com/code/8f1de6493c35cadd0976532b36a23c2fb09bc7b2
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.
I am working with Mailchimp API, and trying to pass the user name from my form to the list.
Mailchimp has a nested structure for an actual user name, and I don't understand how to correctly write code for it.
The JSON data structure looks like that:
{
"email_address": xxx#xxx.com
"merge_fields": {
"FNAME":
"LNAME":
}
}
To send the post request the script using a function with post method
$result = $MailChimp->post("lists/$mailchimp_list_id/members", [
'email_address' => $subscriber_email,
'status' => 'subscribed',
//'merge_fields'['FNAME'] => $subscriber_name;
]);
I try to send 'merge_fields'['FNAME'] => $subscriber_name;
Can anyone explain me how to get inside the JSON with PHP?
Try like this
$jsonArray = json_encode(array('0' =>'test','1' => 'test2'));
json_encode will convert your php array to json format
If you want to decode your json array to php array then use json_decode
$phpArray = json_decode('Any json encoded array');
Okay, this is the best way to work with JSONs in PHP:
Add this to get the full JSON Body:
$json = file_get_contents('php://input');
Validate the json. I work with the Respect Validator.
https://github.com/Respect/Validation/blob/master/docs/Json.md
if(v::json()->validate($json)){
$whatever = new whatever($json);
}
Normalize the json object with a php class
class whatever{
public $email;
public $merged_fields;
function __construct($json){
$json = json_decode($json);
if($json->email){
$this->email = $json->email
}else{
echo "Error";
}
}
}
Use jsonSerializable for encoding. This is a really good HowTo:
http://www.sitepoint.com/use-jsonserializable-interface/
First create a PHP data structure to match the required JSON structure and then json_encode() that structure.
The {} means object in JSON
The [] means array in JSON
<?php
$inner = new stdClass();
$inner->FNAME = $subscriber_first_name;
$inner->LNAME = $subscriber_last_name;
$member = new stdClass();
$member->email_address = 'xxx#xxx.com';
$member->merge_fields = $inner;
$json_string = json_encode($member);
I want to create a more complex JSON Array where a customer (which has a name) has many phonenumbers so that i can parse it in PHP and i need your help.
i.e.:
public Class ContactVO
{
public String diplayname;
public ArrayList<PhoneVO> phonenumbers = new ArrayList<PhoneVO>();
}
public Class PhoneVO
{
public String number;
}
Can s.o. give me an example how to create the above 1:N structure as JSON Array and how to parse it via PHP?
I put everything in a ArrayList and added the GSON library to may project.
The result is:
[
{"contact_id":"1","displayname":"Bjyyyyy","phonenumbers":[{"number":"066-6228"}]},
{"contact_id":"2","displayname":"Rainer Unsinn","phonenumbers":[{"number":"(066) 214-52"}]},
{"contact_id":"3","displayname":"Dieter karpenstein","phonenumbers":[{"number":"06621716669"}]},
{"contact_id":"4","displayname":"Sido","phonenumbers":[{"number":"(085) 011-1555"}]},
{"contact_id":"5","displayname":"Jochen Müller","phonenumbers":[{"number":"01773313261"}]}
]
How should the receiving PHP File lookslike to parse that?
Are you just looking for the json_decode function?
$fromPost = $_POST['contact'];
$object = json_decode($fromPost, true); // Read the doc to decide whether you want the "true" or not
var_dump($object);
Edit:
You could have something like that (not tested)
$string = '[
{"contact_id":"1","displayname":"Bjyyyyy","phonenumbers":[{"number":"066-6228"}]},
{"contact_id":"2","displayname":"Rainer Unsinn","phonenumbers":[{"number":"(066) 214-52"}]},
{"contact_id":"3","displayname":"Dieter karpenstein","phonenumbers":[{"number":"06621716669"}]},
{"contact_id":"4","displayname":"Sido","phonenumbers":[{"number":"(085) 011-1555"}]},
{"contact_id":"5","displayname":"Jochen Müller","phonenumbers":[{"number":"01773313261"}]}
]';
$decoded = json_decode($string);
foreach($decoded as $person) {
echo $person['displayname'] . "\n";
foreach($person['phonenumbers'] as $phone) {
echo $phone['number'] . "\n";
}
}