create json response without brackets [] in php - php

I am trying to send json response as :
{"id":13,"user_id":4,"play_list_name":"My Play List12","section":1,"created":"2017-04-14T05:46:47+00:00","status":1}
but the webservice is generating json as:
[{"id":13,"user_id":4,"play_list_name":"My Play List12","section":1,"created":"2017-04-14T05:46:47+00:00","status":1}]
Below is my web service:
$response_data=$this->MyPlaylists->findById($id)->toArray();
echo json_encode($response_data); die;
However below json_encode is generating valide response:
$response_data=array('response'=>0,'message'=>'This is already added in db');
echo json_encode($response_data); die;
Output:
{"response":"already added","message":"This is already added in db"}

toArray() will convert your Object in Array. So you don't need to add toArray() in your result.
$response_data=$this->MyPlaylists->findById($id);// without toArray()
echo json_encode($response_data); die;
Hope above will work and if not, then try the below code,
$response_data=$this->MyPlaylists->findById($id)->toArray();
echo json_encode(
isset($response_data[0]->id)?
$response_data[0]:
array('response'=>0,'message'=>'This is already added in db')
);die;

Related

Get the value from Rest post API

Output when success
string(66)
"{"status":true,"message":"success","data":{"amountDue":"-504.20"}}"
Output when error
string(119) "{"status":false,"message":"An error occured while getting
full subscriber profile: Subscription not found MPP servers"}"
How should I write in php to get the amount due from the output? I am new to REST api. Can someone show me ? Thank you
That is a JSON-encoded response. Use json_decode() to convert the string back into an array, and then access the array element:
$output = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$results = json_decode($output,true);
if($results["status"])
{
echo "Success! Data: " . print_r($results,true);
}
I assume that you can at least send proper request to the endpoint and you are able to capture the response.
You receive a json string which must be parses so if:
$response = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$responseArray = json_decode($response, true);
Then you will get a responseArray as associated array (the second parameter) so you can get amount due like that
$amountDue = $responseArray['data']['amountDue'];
You could also parse json data into an StdClass which turn all fields in json into an object's property. To do that abandon the second parameter in json_decode function
$resultObj = json_decode($response);
$amountDue = $resultObj->data['amountDue'];
All depends on your requests.
To read more about json_decode try documentation

PHP: SOAP Webservice with JSON responce

I am developing a webservice in PHP using SOAP and I have to return the response in JSON format. Webservice method is simple. It takes an array as input and should return JSON object. Registering the method in webservice is like this:
$server->register(
'getProducts',
array('arr' => 'xsd:array'),
array('return' => 'xsd:json')
);
And I am doing this inside the method:
$sql3 = "SELECT name, price from products WHERE status_id=$staus_id and cat_id=$cat_id";
$result3 = $conn->query($sql3);
$row3 = mysqli_fetch_all($result3, MYSQLI_ASSOC);
$json = json_encode($row3);
return $json;
Whereas on client side I am doing this to catch the object and echo it:
$response = $client->getProducts($param);
echo $response;
But When I run the client side script, it gives nothing (an empty json object):
When I change the return type of the method to string in $server->register and I return an actual string in the method, it works fine but it doesn't in case of JSON object. Any help?
I am guessing here, since you did a json_encode on the server side, you must do a json_decode on the client side.
Change the code on the last line from:
echo $json;
to
echo json_decode($json);

Getting Guzzle Twitter response data

Hopefully the solution to this is a lot more simple than what I've been trying!
I've got a Symfony 2.3 app where I'm attempting to get the number of followers of a Twitter users account. I get back data but I can't access it by array key/index values.
Controller Action:
public function twitterAction(){
$twitterClient = $this->container->get('guzzle.twitter.client');
$response = $twitterClient->get('1.1/followers/ids.json?screen_name=ACCOUNTNAME')
->send()->json();
return $this->render('CatablogSiteBundle:Default:status.html.php', array('response' => $response));
}
View:
<?php
var_dump($response);
echo '<br><br>';
echo gettype($response);
echo '<br><br>';
echo $response[0];
?>
I get back data that I want to use from var_dump, gettype responds with type Array , and attempting to reference $response[0] will fail completely.
What can I do to access data inside the response Object?
edit:
Of course I can't echo $response[0] ... (wrong type) don't try and code tired guys. Solved whilst going over NHG's answer, which is still helpful for anyone having problems with Guzzle.
If I understood TwitterClient extends Guzzle\Service\Client (based on https://github.com/RobinvdVleuten/guzzle-clients/blob/master/Twitter/TwitterClient.php, isn't it?). So, let's try this one:
echo $response->getBody();
// for getting body
echo $response->getHeader('Content-Length');
// for getting Content-Length body
$data = $response->json();
// for getting response in json format
Docs: http://guzzlephp.org/tour/http.html#using-a-client-object

Accessing tweets from home timeline in Twitter using oAuth in PHP?

I am trying to print the first tweet in the user timeline.
$hometimeline = $twitterObj->get_statusesHome_timeline();
$stream=$hometimeline->responseText;
$user=$stream[0]->user;
$tweet=$user->text;
echo $tweet;
This just won't print anything. What am I doing wrong here?
If I echo $hometimeline->responseText it shows on the screen
[
{"in_reply_to_status_id_str":null, "coordinates":null, "geo":null, "user":{"profile_use_background_image":true,"text":"I am back",....},"id_str":"121212"},
{ ... so on}
]
you are getting a json string as response. Use json_decode to parse the response and you will be able to manage it as array o stdobject
do this just before interact with the response
$stream = json_decode( $hometimeline->responseText, true);
Edit
remember you can always use print_r to debug
Try this instead:
$hometimeline = $twitterObj->get_statusesHome_timeline();
$stream = json_decode( $hometimeline->responseText );
$user=$stream[0]->user;
$tweet=$user->text;
echo $tweet;
json_decode turns the JSON string that you are receiving into a PHP object.

Extract Data from a Website using PHP

I am trying to get PHP to extract the TOKEN (the uppercase one), USERID (uppercase), and the USER NAME (uppercase) from a web page with the following text.
{
"rsp":{
"stat":"ok",
"auth":{
"token":"**TOKEN**",
"perms":"read",
"user":{
"id":"**USERID**",
"username":"**USER NAME**",
"fullname":"**NAME OF USER**"
}
}
}
}
(This is from the RTM api, getting the authentication token of the user).
How would I go about doing this? Thanks!
EDIT:
how would i get task name "Buy Milk!" & the due date of the task"2011-02-28T.." using json_decode and php here? Thanks!
{
"rsp":{
"stat":"ok",
"tasks":{
"rev":"REV_NUMBER",
"list":{
"id":"ID_NUMBER",
"taskse­­ries":{
"id":"ID_NUMBER",
"created":"2010-11-16T00:01:50Z",
"modified":"2011-02-28T05:09:36Z",
"name":"Buy Milk!",
"source":"js",
"url":"",
"location_id":"",
"rrule":{
"every":"1",
"$t":"FREQ=W­­EEKLY;INTERVAL=1"
},
"tags":[
],
"participants":[
],
"notes":[
],
"task":{
"id":"ID_NUMBER" ­­,
"due":"2011-02-28T05:00:00Z",
"has_due_time":"0",
"added":"2011-02-21T05:04:49Z",
"completed":"",
"deleted":"",
"priority":"2",
"postponed":"0",
"estima­­te":""
}
}
}
}
}
}
As Delan suggested, use json_decode. Here is an example of how you would use json_decode to extract the information you require.
// your json string
$string = '{"rsp":{"stat":"ok","auth":{"token":"**TOKEN**","perms":"read","user":{"id":"**USERID**","username":"**USER NAME**","fullname":"**NAME OF USER**"}}}}';
// parse json string to an array
$array = json_decode($string, true);
// auth token
echo $array['rsp']['auth']['token'];
// user details
echo $array['rsp']['auth']['user']['id'];
echo $array['rsp']['auth']['user']['username'];
echo $array['rsp']['auth']['user']['fullname'];
UPDATE I've updated the code to use json_decode's $assoc parameter to convert from an object to an assoc array.
ANOTHER UPDATE To answer your updated question..
how would i get task name "Buy Milk!" & the due date of the task"2011-02-28T.." using json_decode and php here? Thanks!
This code would work to get the values that you want.
//string(9) "Buy Milk!"
echo $array['rsp']['tasks']['list']['taskseries']['name'];
// string(20) "2011-02-28T05:00:00Z"
echo $array['rsp']['tasks']['list']['taskseries']['task']['due'];
This code isn't ideal, but it gets the job done for you.
If the string is JSON, json_decode in PHP will do the trick. It's was implemented in PHP 5.2.0.
http://www.php.net/manual/en/function.json-decode.php

Categories