I am trying to send JSON object from PHP web service to my android app. Initially for checking if my PHP file returns the JSON value, I typed the url in browser and got correct value as desired. To check my android code, I executed the code using correct host url but got only '[]' as output in logcat. For debugging purpose, I created a free web hosting and database in hosthinger.com. This time the exact same php and android code worked fine, giving me the desired output. List of things we did to ensure there is no mistake:
Checked the collation of database in both hostings (utf8_unicode_ci)
Both the hosting returned correct value in browser.
Is there any specific PHP configuration for JSON objects?. Or am I missing any header information? I'm not getting a clue why code is working perfectly in one hosting and not in the other.
Here is my PHP code:
<?php
include ('mysqlconnection.php');
$mobile = $_POST['mobile_number'];
$output = array();
$query="select name,status from content;";
$sql = mysql_query($query);
while($row = mysql_fetch_assoc($sql)) {
$output[]= array( 'imagename' => $row['name'], 'status' => $row['status'] );
}
echo json_encode($output);
?>
May be you need to specify content.type in your php:
header('Content-Type: application/json');
You should use an output buffer with a application/json header, instead of just echoing the json_encode() output.
Some servers tend to give errors when you're working with MySQL, check the configurations. And do not use mysql_* functions, use PDO or at least mysqli instead.
You should check for possible errors in your code, check your connection, query results etc.,THEN you can generate a JSON to give output.
Make sure your server's error_reporting is set to 0. Sometimes servers print out warnings, notices and error messages that messes up your output.
You can use Google Chrome's PostMan Extension to view the results of your web service. It also shows output as json parsed.
Related
I want to get movie Rating from IMDB website.
For example, I have a url http://p.media-imdb.com/static-content/documents/v1/title/tt1520211/ratings%3Fjsonp=imdb.rating.run:imdb.api.title.ratings/data.json
Run it and you can see the movie rating is 8.7 and I wan to get it, so I used this query:
$s="http://p.media-imdb.com/static-content/documents/v1/title/tt1520211/ratings%3Fjsonp=imdb.rating.run:imdb.api.title.ratings/data.json";
$s = file_get_contents($s);
$s=explode('rating":',$s);
$s=explode(',"rating',$s[1]);
echo $s[0];
But it doesnt work and I don't know why!
I am checking the script out but uhm ye your array contains nothing check it with: print_r($s)
the output is:
Array ( [0] => )
updated
When you show the content it shows:
‹5KOÃ0„ÿJµ'šÄvÞ9U‚.‰³›LÁ¢y`o*UUþ;v ·õÎìÌg3ôÇØj6ãgl—ñáF‡¬©¹Ñ4#ÓH µ†ÏxÛlŽödñ³ÀñKï¥4Óe*€èˆ2¤DÕŠH×U‘zÔ"‡?q°Ó¡5^5i\gÕ’Ü´Ø¡ðÀ×Ùd“žMÌ¡õŸ.ԚЗlÛ„YæJ()/l«€ù…݇>{ÿKí_0_Þa BÔÚR£„{êôè¿æ lx¤š*.ï§iÙC—…Rb]1“$æ6
so your explode will also be checked to that string.
Code:
$s="http://p.media-imdb.com/static-content/documents/v1/title/tt1520211/ratings%3Fjsonp=imdb.rating.run:imdb.api.title.ratings/data.json";
$s = file_get_contents($s);
/*$s=explode('"rating":',$b);
$s=explode('"rating":',$b[1]);
print_r($s);*/
print($s);
updated:
also check the code with JSONLint
it seems like it has an error
I think you can find more in this question for your answer:
json to php array using file get contents
I assume the PHP.ini setting allow_url_fopen is disabled, which means that remote URIs (ie http(s), etc) can not be opened using the file family functions (fopen,..)
Please also refer to its config value description according to which it is a system wide setting, so I think you can not override it using ini_set().
Alternatively you could use the cURL extension, for details on how to use it please refer to its documentation.
Please run php info to check if the allow_url_fopen is set to ON
php_info();
But use the CURL for getting the content, which simulating an actual web client.
Do not turn on this option, because it's not a good for security purposes
I have the following problem : On my local development server PHP 5.3.10 / Apache 2 every things goes right. When I run the same code with the production server PHP Version 5.2.13 / Apache 2 the code fail but on certain conditions not always.
More details :
The context : I have a dojox.data.grid table on the screen that can be updated. The modified data is correctly passed to the server as a JSON string. Like this :
data = {
"deletedItems":{}
,"newItems":{}
,"modifiedItems":{
"2890":{"idFacture":"2890"
,"idClient":"175"
,"idAffaire":"1323"
,"idContrat":"2234"
,"raisonSociale":"xxxxxx"
,"nomAffaire":"xxxxxx"
,"nrFacture":"xxxxx"
,"dateFacture":"2012-12-06"
,"montantFacture":"160000.00"
,"pourcentageFacture":"64.88"
,"pourcentageCalcule":"32.44"
,"noteFacture":""
,"dateTransfert":""
,"aTransferer":true
,"typeDocument":"Facture"
,"factureSoldee":false
,"montantTotalHeures":"0.00"
,"pourcentageTotalHeures":"0.00"
,"montantTotalMateriel":"0.00"
,"pourcentageTotalMateriel":"0.00"
,"montantTotalSousTraitance":"160000.00"
,"pourcentageTotalSousTraitance":"40.94"
}
,"2892":{"idFacture":"2892"
,"idClient":"50"
,"idAffaire":"1649"
,"idContrat":"2713"
,"raisonSociale":"xxxxx"
,"nomAffaire":"xxxxx"
,"nrFacture":"xxxxx"
,"dateFacture":"2012-12-07"
,"montantFacture":"12004.50"
,"pourcentageFacture":"0.00"
,"pourcentageCalcule":"41.94"
,"noteFacture":""
,"dateTransfert":""
,"aTransferer":true
,"typeDocument":"Facture"
,"factureSoldee":false
,"montantTotalHeures":"12004.50"
,"pourcentageTotalHeures":"41.95"
,"montantTotalMateriel":"0.00"
,"pourcentageTotalMateriel":"0.00"
,"montantTotalSousTraitance":"0.00"
,"pourcentageTotalSousTraitance":"0.00"
}
}
}
You can see that the data contains three elements "deletedItems" (empty), "createdItems" (empty) and "modifiedItems".
In the php code i have the following commands :
$srvJson = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
$data = $srvJson->decode($data);
Where $data is filled like above. Normally after that last statement the folowing PHP variables are set :
$data["deletedItems"]
$data["createdItems"]
$data["modifiedItems"]
Here is the problem : if on the production server there are a lot of modified rows (about > 30) in the table, the modified data is correctly passed to the serveur BUT $data["modifiedItems"] is not set ??? If I just modify the dataset for a few rows $data["modifiedItems"] is well set.
I can modify the whole data set piece per piece, but not the whole dataset in one time.
I suppose this is a question of server settings but what ?
I would appreciate any suggestion.
Best regards,
Roger
PS : Sorry for my english
Since it is not valid JSON (checked with http://jsonlint.com/) the results of json_decode() in PHP 5.3.10 and PHP 5.2.13 are different!
While 5.3 returns nothing 5.2.13 returns the initial string. Probably your code has somewhere some error corrections...
See the different results of the different PHP version on 3v4l.org!
When us remove data = from your JSON does not throw errors..
Based on your above issue, you can check following things on server
magic_quotes are open or closed on server similiar to local server
Does Services_JSON is compitable to PHP 5.3
Services_JSON is pear php library so please check that it is working properly with all extension of php
http://pear.php.net/bugs/search.php?cmd=display&package_name%5B%5D=Services_JSON
Or you can use the default php json library for encode and decode
May this will help you
I'm sure this is similar to other questions, but I have tried the solutions, and couldn't get it to work.
I'm trying to get the location of an IP address, decode the json, and print it. I actually plan to put it into a database, but Im not even sure why I cant get anything to print to the screen.
$ip = $_SERVER['REMOTE_ADDR'];
$json = file_get_contents("http://api.hostip.info/get_json.php?ip=".$ip);
$local = json_decode($json,true);
thanks.
A. When you mean I cant get anything to print to the screen. definitely you can get anything because you did not output anything to screen.
error_reporting(E_ALL);
$ip = $_SERVER['REMOTE_ADDR'];
$json = file_get_contents("http://api.hostip.info/get_json.php?ip=".$ip);
$local = json_decode($json,true);
echo $local['city'] ;
print $local['country_name'] ;
var_dump($local);
B. It would also mean that allow_url_include set to Off which would not allow file_get_contents load a information from another domain
Firstly, the code you've provided does not actually print anything, which would explain why you're getting a blank screen. I assume you're doing something like echo $local; later in the program, but if not, that'll be the problem.
Assuming that isn't the issue....
Two possibilities:
file_get_contents() is returning an error.
json_decode() is returning an error.
Firstly, you should add some additional error trapping in your code to determine which one is the problem.
If you have PHP set to not display errors, consider switching them on so you can see any errors that are generated. Or else look at your server log to see the errors.
file_get_contents() may fail if the URL is invalid. It may also fail if your PHP installation is set to not allow URLs via the file handling functions. If this is the case you'll need to change your php.ini settings. If you can't do that, you'll have to load the file via a different method (eg Curl).
json_decode() is only likely to fail if the string it gets is invalid JSON. You should check the output of the URL to confirm that it looks right, and check it something like firebug to ensure it is valid.
Hope that helps.
I am trying to make a simple AJAX calling in PHP and have a problem with Internal error 500. When I click on the link, so the data are successfully loaded - this I see through FireBug, but I got the error above. It's on localhost.
When I try to set to the URL of a browser the address, that is called by AJAX, so the content is successfully loaded.
Where I should start to search the problem - or what could be wrong?
EDIT: in apache log is nothing weird, looks fine.
If after checking your php error log you don't find any issues, could it be your javascript AJAX call expects results to be returned in a specific format like JSON?
If this is the case, you need PHP to set the correct content type header when it is responding to the AJAX call, like so:
header('Content-type: application/json');
So in context, this might look something like:
$some_data = array(
'user_id' => 47,
'first_name' => 'Mike',
);
header('Content-type: application/json');
echo json_encode($some_data);
Look in the PHP error logs, or perhaps even your web server's error log.
Or if your script spews out errors to the client (which it hopefully doesn't do, at least not in production), try taking a look at the response in Firebug.
You most likely have a bug in your PHP. It doesn't matter if it is an AJAX call. Look at your server logs.
I'am building simple Ajax application (via jquery). I have strange issue. I found where the problem is, but I don't know how to solve it.
This is simple server-side php code:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
On the client side, the error "Invalid JSON" is thrown.
I have discovered that if I delete require function, everything work fine.
Just for information, the "some.php" is an empty php file. There is no error when I open direct php files.
So, conclusion: I cant use require or include function if I want to use ajax?
Use Firebug to see what you're actually getting back during the AJAX call. My guess is that there's a PHP error somewhere, so you're getting more than just JSON back from the call (Firebug will show you that). As for your conclusion: using include/require by itself has absolutely no effect on the AJAX call (assuming there are no errors).
Try changing:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
To:
<?php
$return = array(
'pageContent' => 'test'
);
echo json_encode($return);
?>
The problem might have to do with $return not being declared as an array prior to use.
Edit: Alright, so that might not be the problem at all. But! What might be happening is you might be echoing out something in the response. For example, if you have an error echoing out prior to the JSON, you'd be unable to parse it on the client.
if the "some.php" is an empty php file, why do you require it at all?!
require function throws a fatal error if it could't require the file. try using include function instead and see what happens, if it works then you probably have a problem with require 'some.php';
A require call won't have any effect. You need to check your returned output in Firebug. If using Chrome there is a plugin called Simple REST Client. https://chrome.google.com/extensions/detail/fhjcajmcbmldlhcimfajhfbgofnpcjmb through which you can quickly query for stuff.
Also, it's always good to send back proper HTTP headers with your response showing the response type.
It's most likely the BOM as has been discussed above. I had the same problem multiple times and used Fiddler to check the file in hex and noticed an extra 3 bytes that didn't exist in a prior backup and in new files I created. Somehow my original files were getting modified by Textpad (both in Windows). Although when I created them in Notepad++ I was fine.
So make sure that you have your encoding and codepages set up properly when you create, edit, and save your files in addition to keeping that consistent across OSes if you're developing on windows let's say and publishing to a linux environment at your hosting provider.