Could some one please help me out on this I have the following json string
string(1223) "YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"google","Result":[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}]}})"
But I cannot seem to get anywhere with it. Basically I want to just loop out the the results which are
[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}]
Sorry my question is how can I loop or even print the first result for example
{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"}
Your string is not JSON, it is JSON-in-Script. Notice the fragment that says:
YAHOO.Finance.SymbolSuggest.ssCallback(...)
When a browser receives the above mentioned script (actually a javascript code) it will call the YAHOO.Finance.SymbolSuggest.ssCallback function, passing the JSON data as the argument.
You did not mention if you want to access the JASON data on the server side or client? It its server side (PHP) then you can use regular expressions or string replacement functions to extract the portion you like. The you can use json_decode() function to convert the resulting string into an associative array.
Edit ----
A quick and dirty hack for converting JSONP to JSON:
<?php
$text = 'YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"google","Result":[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}]}})';
# //CONVERT JSONP to JSON\\
$text = preg_replace('/.+?({.+}).+/', '$1', $text);
# \\CONVERT JSONP to JSON//
$data = json_decode($text);
var_dump($data);
var_dump($data->ResultSet->Result[0]);
var_dump($data->ResultSet->Result[0]->symbol);
var_dump($data->ResultSet->Result[0]->name);
# etc etc
?>
Your result is not just a JSON string, it's a JSON string prepended by a call to a JSON function. This is quite certainly a JSONP call.
You must write the YAHOO.Finance.SymbolSuggest.ssCallback(data) javascript function and get the Json there. Check the JSONP query, you should be able to alter the name of this backreference function if you want another name, it's usually on of the parameter in the GET query.
Now you are maybe calling it directly from PHP and you are not in js envirronment. so you must write something in your PHP code to remove the YAHOO.Finance.SymbolSuggest.ssCallback( part and the ) at the end before parsing it as JSON data..
Related
I am loading an external JSON file. Which seems to load fine. Im using this script to load it:
$file ="https://creator.zoho.com/api/json/los/view/All_clients?
authtoken=xxx";
$bors = file_get_contents($file);
When i dump the results, I get:
string(505) "var zohoappview55 = {"Borrowers":[{"Full_Name":"Mike Smith","Email":"dadf#gmail.com","Address":"111 S. Street Ct., Aurora, CO, 80012","Position":"Borrower","ID":"1159827000004784102","Mobile":"+13033324675","Application":"Application 1 - 1159827000004784096"},{"Full_Name":"Stacy Smith","Email":"sdfa#gmail.com","Address":"111 S. Street, 80012","Position":"Co-Borrower","ID":"1159827000004784108","Mobile":"+1303558977","Application":"Application 1 - 1159827000004784096"}]};"
Looks like the json has a predefined var zohoappview55 at the begining of the json. Not sure if this is my issue but when i use json_decode it doesn't not decode. If i remove this beginning variable it decodes just fine.
i don't have a way to change this variable or edit the json file as it's a remote file. Does anyone know how to decode it in the native format with the variable at the beginning?
Having a quick look through the API documentation of zoho, it seems it should normally return correct json. It may think that it's a browser requesting the file as a javascript source so you may need to add an Accept header to your request.
This cannot be done with file_get_contents so you will probably need to use curl instead.
Try to perform a normal php curl request with the header Accept: application/json.
See: PHP cURL custom headers for reference.
But as Alex Howansky said in the comment. The API might not be intended for that. In that case you will need to strip the beginning and end of the received document.
My API URL Returned code in browser as shown below. but json_decode($api_url,true); returns null.
i checked json_last_error();, it returns 4(json error syntax).
it worked with json_decode(file_get_contents($api_url),true);
why it isn't work with json_decode. please help
{"dataset":{"id":27153572,"dataset_code":"20MICRONS_A_DEBT","database_code":"DEB","name":"20 Microns Limited,Total Debt","description":"\u003cp\u003e20 Microns Limited(NSE:20MICRONS)-Total Debt(Annual)\u003c/p\u003e","refreshed_at":"2018-09-21T08:04:08.278Z","newest_available_date":"2018-03-31","oldest_available_date":"2005-03-31","column_names":["PERIOD","STANDALONE","CONSOLIDATED"],"frequency":"annual","type":"Time Series","premium":true,"limit":null,"transform":null,"column_index":null,"start_date":"2005-03-31","end_date":"2018-03-31","data":[["2018-03-31",128.56,133.68],["2017-03-31",144.9,151.73],["2016-03-31",155.18,163.41],["2015-03-31",152.8,164.62],["2014-03-31",162.01,176.64],["2013-03-31",148.49,164.73],["2012-03-31",144.67,158.6],["2011-03-31",81.42,120.31],["2010-03-31",84.35,87.35],["2009-03-31",58.62,58.62],["2008-03-31",46.52,null],["2007-03-31",42.46,null],["2006-03-31",40.03,null],["2005-03-31",38.98,null]],"collapse":null,"order":null,"database_id":14992}}
What you are trying to do has no sense. $api_url is just an url so when you try to decode it then it doesn't have a json stucture and it will throw an exeption.
What you should decode is the data that this url returns to you.
So First you should get data from url then use json_decode($api_url,true);.
To get data you can use file_get_contents or curl.
Props to u_mulder who hit the nail on the head but I want to break this down for you a little.
Purpose of file_get_contents():
The file_get_contents() function is an inbuilt function in PHP which is used to read the contents of a file into a string.
Please note that the 'file' can be a file residing on your web server or a remote file (URL), which in essence will give you a web document back.
Purpose of json_decode():
The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable.
With that in mind you can see that performing json_decode on an invalid JSON string or a URL will render your result as NULL.
json_decode('https://www.website.com')
This is essentially what you are doing. performing the file_get_contents inside your json_decode first converts your URL/File ('https://www.website.com') into a string, that string then having JSON is then converted into an array by json_decode.
i need to remove () backslash in my string when using echo json_encode()?
my example..
$song_url = 116e9155e0afc11555cf33dc9c9bd25d.mp3
$resmsg[] = array("Song_name"=>"$song_name","Song_URL"=>"http://www.kbmusique.com/songs/$song_url");
echo json_encode($resmsg);
my output is
[{"Song_name":"djigh araouioui","Song_URL":"http:\/\/www.kbmusique.com\/songs\/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
but i need as
[{"Song_name":"djigh araouioui","Song_URL":"http://www.kbmusique.com/songs/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
Is there a way to solve this? Thank you.
Your comment indicates that you just need to get a copy/pastable URL for testing.
Just parse the JSON and extract the piece of data you need from it. i.e. If you want a text representation of something, then convert the JSON to text, don't try to hack the JSON into a specific form.
You could do this in PHP with json_decode, in a browser with JSON.parse(), or just use a tool such as the Chrome JSONView extension.
I have the following json
country_code({"latitude":"45.9390","longitude":"24.9811","zoom":6,"address":{"city":"-","country":"Romania","country_code":"RO","region":"-"}})
and i want just the country_code, how do i parse it?
I have this code
<?php
$json = "http://api.wipmania.com/jsonp?callback=jsonpCallback";
$jsonfile = file_get_contents($json);
var_dump(json_decode($jsonfile));
?>
and it returns NULL, why?
Thanks.
<?php
$jsonurl = "http://api.wipmania.com/json";
$json = file_get_contents($jsonurl);
var_dump(json_decode($json));
?>
You just need json not jsonp.
You can also try using json_decode($json, true) if you want to return the array.
you're requesting jsonp with http://api.wipmania.com/jsonp?callback=jsonpCallback, which returns a function containing JSON like:
jsonpCallback({"latitude":"44.9718","longitude":"-113.3405","zoom":3,"address":{"city":"-","country":"United States","country_code":"US","region":"-"}})
and not JSON itself. change your URL to http://api.wipmania.com/json to return pure JSON like:
{"latitude":"44.9718","longitude":"-113.3405","zoom":3,"address":{"city":"-","country":"United States","country_code":"US","region":"-"}}
notice the second chunk of code doesn't wrap the json in the jsonpCallback() function.
The website doesn't return pure JSON, but wrapped JSON. This is meant to be included as a script and will call a callback function. If you want to use it, you first need to remove the function call (the part until the first paranthesis and the paranthesis at the end).
If your server implements JSONP, it will assume the callback parameter to be a JSONP signal and the result will be similar to a JavaScript function, like
jsonpCallback("{yada: 'yada yada'}")
And then, json_decode won't be able to parse jsonpCallback("{yada: 'yada yada'}") as a valid JSON string
If country_code( along with closing parenthesis are include in your json, remove them.
This is not a valid json syntax: json
You are being returned JSONP, not JSON. JSONP is for cross-domain-requests in JavaScript. You don't need to use it when using PHP because you aren't affected by cross-domain-policies.
Since you are getting a string from the file_get_contents() function you can do a replacement of the country_code( text (this is the JSONP specific part of the response):
<?php
$json = "http://api.wipmania.com/jsonp?callback=jsonpCallback";
$jsonfile = substr(file_get_contents($json)), 13, -1);
var_dump(json_decode($jsonfile));
?>
Note
This works but JKirchartz's solution looks better, just request the correct data rather than messing around with the incorrect data.
Obviously in this situation, using the correct URL to access the API will return pure jSON.
"http://api.wipmania.com/json"
A lot of people are providing an alternative to the API in use, rather than answering the OP's question, so here is a solution for those looking for a way of handling jSONp in PHP.
First, the API allows you to specify a callback method, so you can either use Jasper's method of getting the jSON sub string, or you can give a callback method of json_decode, and modify the result to use with a call to eval. This is my alternative to Jasper's code example since I don't like to be a copy cat:
$json = "http://api.wipmania.com/jsonp?callback=json_decode";
$jsonfile eval(str_replace("(", "('", str_replace(")", "')", file_get_contents($json)))));
var_dump($jsonfile);
Admittedly this seems a little longer, more insecure, and not as clear to read as Jasper's code:
$json = "http://api.wipmania.com/jsonp?callback=jsonpCallback";
$jsonfile = substr(file_get_contents($json)), 13, -1);
var_dump(json_decode($jsonfile));
Then the jSON "address":{"city":"-","country":"Romania","country_code":"RO","region":"-"} tells us to access the country_code like so:
$jsonfile->{'address'}->{'country_code'};
I think I have the need to take a uri which has been decoded in PHP, and re-encode it.
Here is the situation:
JavaScript passes encoded uri as query string parameter to php script.
PHP script embeds uri as a hidden input value in an html document, responds with the document to a user agent.
JavaScript reads embedded uri and sets location of current document based on value of hidden input.
On Step 2, I am finding that the Uri is fully decoded after reading it in via $_GET. So when I embed the uri in the hidden input, it becomes un-encoded. So I would like to run a PHP script which re-encodes the Uri properly ex:
http://my.example.com/dog walk?is=very great
==>
http://my.example.com/dog%20walk?is=very%20great
Is there a pre-built php function for this or should I just write my own?
PLEASE NOTE: urlencode and urldecode are not the answer to get the desired input/output I have in the example above.
Thanks,
Macy
Are you looking for : http://fr.php.net/manual/en/function.urlencode.php ?
I don't know if will help you, but PHP have 3 useful functions:
$url = parse_url('put the url here');
parse_str( $url['query'], $query ); // generating an array by reference (yes, kinda weird)
echo $query; //in this line, you can encode or decode.
or, if you want to mount a query, you can use http_build_query(); that accepts values from an array, like:
$url = 'http://my.example.com/dog walk?';
$array = Array (
'is' => 'very_great',
);
$url_created = $url . http_build_query($array);
urldecode:
http://www.php.net/manual/en/function.urldecode.php