I am working in Symfony2 and I want to se the content of a Request with a JSON string and use i.e.: $request->get('name') to access the content.
JSON string:
$string = '{
"name":"Bob",
"surname":"White",
"email":"bobwhite#gmail.com",
"nationality":"",
}';
$request = new Request ($query = array(), $request = array(), $attributes = array(), $cookies = array(), $files = array(), $server = array(), $content = $string);
var_dump($request->get('name'));die;
To me the above is a valid way but the var dump gives me null... can anyone see where I m going wrong here...?
You want something like this?
use Symfony\Component\HttpFoundation\Request;
$input = '{
"name":"Bob",
"surname":"White",
"email":"bobwhite#gmail.com",
"nationality":""
}';
$data = json_decode($input, true);
$request = new Request (array(), $data);
var_dump($request->request->get('name'));
die;
Related
I do rest API. To update data using a PUT request
http://train-basic/stations/21?name=tt
Try get data:
$request = Yii::$app->request;
$request = $request->post();
$name = $request["name"];
dump($name);
As a result, I get null. How to fix it?
To get data sent in request body by PUT or PATCH request, you should use getBodyParam() or getBodyParams()
$request = Yii::$app->request;
// returns all parameters
$params = $request->getBodyParams();
// returns the parameter "id"
$param = $request->getBodyParam('id');
https://www.yiiframework.com/doc/guide/2.0/en/runtime-requests#request-parameters
Data from PUT download like POST
$request = Yii::$app->request;
$id = $request->get('id');
$name = $request->get('name');
$days = $request->get('days');
I've been getting this warning after defining the $image variable using the file_get_contents() function:
Warning: file_get_contents(): Filename cannot be empty
Even though I passed a value to $formname with this method call :
Image::uploadImage('postimg', "UPDATE dry_posts SET postimg = :postimg WHERE id = :postid", array(':postid' => $postid),array(':postimg' => $postimg));
$postimg is a file variable in a form. I've tried checking if the file exists, which solved the error but of course nothing was being executed. It seems to not like it whenever I use file_get_contents(), how do I turn this around?
<?php
include_once("connect.php");
class Image
{
public static function uploadImage($formname,$query,$params)
{
$formname = "";
$response = "";
$image = "";
echo 'hello';
//if(file_exists($formname))
//{
echo 'hello';
$image = base64_encode(file_get_contents($_FILES[$formname]['tmp_name']));
//}
$options = array('http'=>array(
'method'=>"POST",
'header'=>"Authorization: Bearer access code here\n".
"Content-Type: application/x-www-form-urlencoded",
'content'=>$image
));
$context = stream_context_create($options);
$imgurURL = "https://api.imgur.com/3/image";
if ($_FILES[$formname]['size'] > 10240000) {
die('Image too big, must be 10MB or less!');
}
//if(file_exists($formname))
//{
echo 'hell0';
$response = file_get_contents($imgurURL, false, $context);
//}
$response = json_decode($response);
//from
//$prearams = array($formname=>$response->data->link);
//$params = $preparams + $params;
//from changes
//$params=array(':postid'=>$postid);
$params = array(':postid' => $params['postid'], ':postimg' => $params['postimg']);
connect::query($query,$params);
}
}
?>
You are unsetting "$formname" here? $formname = ""; So doesn't matter if you pass it in the method call, it will always be empty
How can I read a JSON data response using php?
This is Code :
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
and give me this json data :
{
"original": "This sentnce has some probblems.",
"suggestion": "This sentence has some problems.",
and ...
}
I want to return "suggestion" in a url with $
this is an example :
$user_id = '123456789'
$mytext = '?' // I WANT RETURN "suggestion" HERE !
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
You can use json_decode().
See:
http://php.net/manual/en/function.json-decode.php
You just need to do:
$response = json_decode($response,1);
echo $response['suggestion'];
Setting the second parameter of json_decode() to 1 (true) will return an associative array of the JSON data.
If you want to include it in a URL using your code example:
$user_id = '123456789'
$json = json_decode($response,1);
$mytext = $json['suggestion'];
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
Use json_decode to convert json_response to array.Add second parameter of 'true' to make it an array that you should be familiar with.
Access suggestion variable by specifying it.
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
$data=json_decode($response,true);
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$data['suggestion'];
echo $url;
I am getting this string from CURL response
{status: 'false',description:'5400'}
I want to extract description parameter only.
I want $description = 5400 ;
How to do this ?
You have a bad json response, you have to change your json code and than using the following code you can access the variable.
<?php
$response = '{"status":false,"description":5400}';
$response_array = json_decode($response);
echo $response_array->description;
?>
And if you want to get the value of description with the existing bad json, you can do following thing.
<?php
$response = "{status:'false',description:'5400'}";
$r = explode("description:'", $response);
$description = rtrim($r[1],"'}");
echo $description;
?>
That response is json. Turn it into a PHP array:
$response = "{status: 'false',description:'5400'}";
$response_array = json_decode($response, true);
$description = $response_array['description'];
echo $description;
# Nirali Joshi
If Your JSON with space then it will be write solution
$response = "{status : 'false', description : '5400'}";
$response = str_replace(" ","",$response);
OR
$response = preg_replace('/\s+/', '', $response);
$t_repsonse = explode("description:", $response);
$i_description = str_replace("}","",str_replace("'","",$t_repsonse [ 1 ] ));
OR
$i_description = str_replace("}","",preg_replace('([ "\' ])', '', $t_repsonse [ 1 ]));
$description = $i_description;
Sorry and improve if any mistake founds and thanks
I have a sample JSON Array labeled sample.txt that is sent from a sweepstakes form that captures a user's name and e-mail. I'm using WooBox so the JSON Array sends information over by each entry, so there are two entries here: http://pastebin.ca/3409546
On a previous question, I was told to break the ][ so that JSON_ENCODE can figure the separate entries. I would like to capture just the name and e-mail and import the array to my e-mail database (campaign monitor).
My question is: How do I add JSON variable labels to an array? If you see my code, I have tried to use the label $email. Is this the correct form or should it be email[0] with a for loop?
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$result = $wrap->add($json(
'EmailAddress' => $email,
'Name' => $custom_3_first,
'Resubscribe' => false
));
https://github.com/campaignmonitor/createsend-php/blob/master/samples/subscriber/add.php
This should have been fairly easy: if you have a JSON string and you call json_decode($string, true) on it, you get its equivalent in a PHP variable, plain and simple. From there, you can access it like you would any PHP array, object, etc.
The problem is, you don't have a proper JSON string. You have a string that looks like JSON, but isn't valid JSON. Run it through a linter and you'll see what I mean.
PHP doesn't know what to do with your supposed JSON, so you have to resort to manual parsing, which is not a path I would recommend. Still, you were almost there.
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array('api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}