null on json data - php

I am trying to parse this json data from the url but i get NULL how do i fix this issue.
$source = file_get_contents('http://partners.socialvi.be/e414f702cf3db89a2fe58066bbab369d65b6a058/activities/available.json');
$json = json_decode($source);
var_dump($json);

That's because the API returns the data in JSONP format, not pure JSON. Notice the surrounding onSVJson([]). You'll either have to strip this out, or read the API documentation and try another request format. My guess would be that leaving out the final &callback=onSVJson should do the trick.

That's because if you call the url (go to http://partners.socialvi.be/e414f702cf3db89a2fe58066bbab369d65b6a058/activities/available.json?network_user_id=3459874&max_activities=9&callback=onSVJson with your browser) the json that is returned has no values

Remove the last part of the URL (&callback=onSVJson) and it'll work.
Many APIs offer a feature called JSONP, that allows the JSON to be passed to a callback function, in order to simplify access via cross domain JavaScript. But for PHP you don't need that.
The name of the callback function is typically specified using the callback GET parameter. If you leave that out, no callback function is used - just plain JSON.

Related

PHP urlencode a URL post field

I am using curl to call an API POST and pass 15 post fields, one being an actual wbsite URL. For example
https://www.test.com?URL=https://www.myurl.com;&Name=John
Using urlencode converts the characters in the URL post field and the API receiving the POST call does not recognize it as an actual URL. Is there any way to keep the URL string as is when positing?
If you are using GET query arguments, you need to urlencode the value, then decode it on the backend:
https://www.test.com?URL=https%3A%2F%2Fwww.myurl.com
And then:
urldecode($_GET['url'])
For POST, the same is true for application/x-www-form-urlencoded, but doesn't matter for application/json.
Also, just a heads up, you have an extra ; in your URL, which would make it invalid if you included it.
Edit:
I will additionally add, that in general, it's good practice to always urldecode values received from query arugments/form data. The general thought here being that, while you may not want urlencoded data, that's the way the web is built - You should build your code in a way that it's up to the client. This is considered an important step in data sanitation, and should always happen before validation.
You can use php builtin method to decode the url encoded data.
$actualUrl = urldecode ($_GET ['url']);

How to return raw string after calling an API (not json-formatted nor xml-formatted, just raw string)

Calling the REST API or the SOAP API will format the returned string to respectively JSON and XML.
However I need the string returned by the service method to be a raw string, with no formatting whatsoever.
The reason behind that is that the service's method calls a legacy model that returns a complex response ; and this response should be transmitted as-is, without any formatting.
I ended up using this dirty solution:
exit('raw text message');
This by passes Magento's JSON wrapper, and echoes directly the wanted text.

Convert key-value JSON to object and refer individual values directly

I am making a web app. In one part of it, I have JS send a string(in json format) to PHP.
The value php receives is:
{"date":"24-03-2014","Cars":["Cheap","Expensive"]}
Now, this is saved in a variable $meta. The problem I am facing is, as to how do I convert this string into an object and reference each individual entry separately.
I have tried json_decode and json_encode
and then I have referenced each variable using $meta.["date"] and $meta.date but nothing seams to work. I am getting just { as the output.
What's the correct way to do this?
$str = '{"date":"24-03-2014","Cars":["Cheap","Expensive"]}';
$obj = json_decode($str);
echo $obj->date;
// 24-03-2014
Usually a $my_obj = json_decode($_POST['jsonstring'], 1); (true supply means it'll be returned as an assoviative array) should be the way to go. If I were you I'd probably try a var_dump($my_obj); to see what actually comes through. If it doesn't work you'll want to make sure that you correctly submit a valid json string, e.g. JSON.stringify();
You should check out the PHP doc page for json_decode here.
By default, unless you pass true as the second parameter for json_decode, the function call will return an object, which you can access the members of by using:
$meta->date
The arrow operator will allow you to access object values, not the square brackets or a dot.

JSON in uri request

What if I pass my searching params in uri request in json-format like this:
http://example.com/?search={"title":"Some+Title","category":12}
instead of
http://example.com/?title=Some+Title&category=12
Before decode json-request I can filter it with some functions like strip_tags(), strpslashes(), etc... But I can do the same with $_SERVER['QUERY_STRING'] with serialize()/unserialize(). Or apply string-filters to N string-params of request, not once to whole request.
Which way do you think will be better, usable and faster to process?
With json
$request = $_GET['search'];
$request = stripslaches(strip_tags($request));
$params = json_decode($request);
The characters { and } are unsafe according to RFC 1738 2.2. They must therefore be encoded before being transferred over a network.
The character : is reserved according to RFC 1738 2.2. It must therefore be encoded before being transferred over a network unless it is used for the purpose for which it was reserved.
Don't use $request = striplashes(strip_tags($request)). If $_GET['search'] does not json_decode sucessfully, treat it as faulty input; don't try to fix it.
Isn't it better to use http_build_query instead of passing JSON throw URL? HTTP_build_query is specially designed to pass data throw url params.
Applying this filter to whole param_str of URL may cause unexpected behaviour, besides fact that is actually little bit faster.
I think that you should pass every one parameter throw your filter functions.
Sending an encoded JSON string is possible, as any string (you should urlencode and urldecode it though, no stripping needed) but it's not really a good way to do it - use the standard way of passing data in request - if you have only simple data to send, just translate it into traditional GET variables (it's really easy, e.g. with http_build_query as Tomasz suggests). You may also run into difficulities with the request URI length (see What is the maximum length of a URL in different browsers?) if you pack too much data into the JSON object.
Why don't you just represent everything with JSON?
http://www.example.com/{"article":"something","page":12,"fragment":"#menu"}
Query strings are already used to represent flat lists of key-value pairs, so what problem does your JSON solution solve? You'll just be adding a new layer of complexity without any benefits.

PHP: How to receive JSON array from iPad app

Disclaimer: I am fairly new to using json.
I am trying to use php to receive json data from an iPAd application. I know how to convert json to an array in php, but how do I actually receive it and store it into a variable so it can be decoded?
Here are a couple examples that I have tried based on google and stackoverflow searches.
$json_request = #file_get_contents('php://input');
$array = json_decode($json_request);
AND ALSO
$array = json_decode($_POST['data'], true);
Any suggestions?
You have the basic idea already.
you should test that the value is set and also strip extra slashes from the incoming string before trying to parse it as JSON.
if(isset($_POST['data'])){
$array = json_decode(stripslashes($_POST['data']),true);
//$array now holds an associative array
}//Data Exists
It also would not be a bad idea before you start working with the array to test that the call to json_decode() was successful by ensuring that $array isn't null before use.
If you do not fully trust the integrity of the information being sent you should do extended checking along the way instead of trusting that a given key exists.
if($array){ // Or (!is_null($array)) Or (is_array($array)) could be used
//Process individual information here
//Without trust
if(isset($array['Firstname'])){
$CustomerId = $array['Firstname'];
}//Firstname exists
}//$array is valid
I in-particular like to verify information when I am building queries dynamically for information that may not be required for a successful db insert.
In the above example $_POST['data'] indicates that what ever called the PHP script did so passing the JSON string using the post method in a variable identified as data.
You could check more generically to allow flexibility in the sending method by using the $_REQUEST variable, or if you know it is coming as via the get method you can check $_GET. $_REQUEST holds all incoming parameters from both get and post.
If you don't know what the name of the variable coming in is and want to play really fast and loose you could loop over the keys in $_REQUEST trying to decode each one and use the one that successfully decoded (if any). [Note: I'm not encouraging this]

Categories