JSON with Variable At Beginning? - php

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.

Related

Load Json data with php giving an error

I am using this code to try to get json data from many json files using yql to compile them into one json.
My yql query is in this format:
select * from json where
url="http://ebird.org/ws1.1/data/obs/region_spp/recent?rtype=subnational2&r=US&sci=Dendrocygna%20autumnalis&fmt=json"
or url = "http://ebird.org/ws1.1/data/obs/geo_spp/recent?lng=-119.859512&lat=34.410240&sci=Dendrocygna%20autumnalis&dist=49&back=14&maxResults=10000&fmt=json&includeProvisional=true"
and itemPath = "json.json"
I rawurlencode the above to obtain the q= part of the yql query url. Then i get this outputted url. It works fine when copy and paste the echoed url into my browser, but when i try to use file_get_contents on the url I get this:
cbfunc({"error":{"lang":"en-US","diagnostics":{"publiclyCallable":"true"},"description":"Query syntax error(s) [line 1:3675 missing EOF at '_']"}});
So I am asking, why does it not work when I am using it with file_get_contents, but does when I am using the url in my browser. Also, is there a smarter/easier way to use multiple json files together with php? I tried using curl to pull the yql json and got a weird output like:
8<\/howMany>34.4136<\/lat>-119.8756<\/lng>L615794
This method would be fine, but I don't know how to get it into a useable array.
Try to use urlencode() instead of rawurlencode(). The system you're sending it to may not like the encoding.

Remove double-quotes from a json_encoded string on the keys

I have a json_encoded array which is fine.
I need to strip the double-quotes on all of the keys of the json string on returning it from a function call.
How would I go about doing this and returning it successfully?
Thanks!
I do apologise, here is a snippet of the json code:
{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}
Just to add a little more info:
I will be retrieving the JSON via an AJAX request, so if it would be easier, I am open to ideas in how to do this on the javascript side.
EDITED as per anubhava's comment
$str = '{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}';
$str = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $str);
echo $str;
This certainly works for the above string, although there maybe some edge cases that I haven't thought of for which this will not work. Whether this will suit your purposes depends on how static the format of the string and the elements/values it contains will be.
TL;DR: Missing quotes is how Chrome shows it is a JSON object instead of a string. Ensure that you have Header('Content-Type: application/json; charset=UTF8'); in PHP's AJAX response to solve the real problem.
DETAILS:
A common reason for wanting to solve this problem is due to finding this difference while debugging the processing of returned AJAX data.
In my case I saw the difference using Chrome's debugging tools. When connected to the legacy system, upon success, Chrome showed that there were no quotes shown around keys in the response according to the debugger. This allowed the object to be immediately treated as an object without using a JSON.parse() call. Debugging my new AJAX destination, there were quotes shown in the response and variable was a string and not an object.
I finally realized the true issue when I tested the AJAX response externally saw the legacy system actually DID have quotes around the keys. This was not what the Chrome dev tools showed.
The only difference was that on the legacy system there was a header specifying the content type. I added this to the new (WordPress) system and the calls were now fully compatible with the original script and the success function could handle the response as an object without any parsing required. Now I can switch between the legacy and new system without any changes except the destination URL.

cutting special chars in folder name when using GET

I've been visiting stackoverflow.com for a long time and always found the solution to my problem. But this time it's different. That's why I'm posting my first question here.
The situation looks like this: My website provides a directory explorer which allows users to download whole directory as a zip file. The problem is I end up with error when I want to download a dir containg special characters in it's name, i.e. 'c++'. I don't want to force users to NOT name their folders with those special chars, so I need a clue on this one. I noticed that the whole problem comes down to GET protocol. I use ajax POST for example to roll out the directory content, but for making a .zip file and downloading it I need GET:
var dir_clicked = $(e.target).attr('path'); //let's say it equals '/c++'
window.location = 'myDownloadSite.php?directory_path='+dir_clicked;
I studied whole track of dir_clicked variable, step by step, and it seems that the variable in adress is sent correctly (I see the correct url in browser) but typing:
echo $_GET['directory_path']
in myDownloadSite.php prints
'/c'
instead of
'/c++'
Why the GET protocol is cutting my pluses?
You can use:
encodeURIComponent() //to get the url then use
decodeURIComponent() //to decode and access ur filename.
Use urlencode() and urldecode() on server side.
Try encoding your URI with encodeURI(url) JavaScript function.
window.location = encodeURI('myDownloadSite.php?directory_path=' + dir_clicked);
Maybe use encodeURIComponent() and then remove all %xx occurrences?
When the information is posted it is encoded with special chars, sounds like you just need to decode them before using the information.
You can use php function urldecode() to decode the folder names before using them...
$_GET[directory_path]=urldecode($_GET[directory_path]);

Problem with php and json

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..

Push JSON Encoded Data To Website in what format?

I need to push some JSON data to my website which I would like to read in PHP. What type of file should I make this? A PHP file with the JSON inside of a variable? I understand how to make a text file with JSON encoded data in it, but how do I get this into PHP? Should I use a PHP include with the JSON-encoded data in it assigned to a variable? Or should I read the file from PHP and put the contents into a variable?
Save your json string as plain text, then you can use:
$file = yourfile
$data = file_get_contents($file);
$parsed = json_decode($data);
// compacted:
$parsed = json_decode(file_get_contents($file));
See file_get_contents() and json_decode().
The advantage of doing this (versus storing it in a PHP file then including it) is that now any program or language that understands JSON can read the file.
The question is too vague for a definite "do this" answer, but here are some options and what they might be most suitable for:
Turn the json data into a PHP data structure. If this is a one-time thing (meaning you won't be getting a new json file every day or week or hour), then reading a file (file_get_contents) and parsing JSON (json_decode) for every request is a pretty big waste of resources since that data isn't changing on a regular basis. Just turn JSON key/value objects into PHP associative arrays, JSON strings into PHP strings, etc.
Just serve the json file. If this is data that will just wind up going to the client to be used in javascript anyway, there's no need to do anything special with it on the server, just parse the json on the client.
Put it in a database. This may be a little heavy-handed, but if you really need it in PHP and not just the client, and it is going to be changing or growing on a regular basis, it may be worth it to have something that handles this use case appropriately.

Categories