I'm trying to record data that is being posted to my server to a text file. An example of the data that is being sent to my server is located here:
http://dev.datasift.com/docs/push/sample-output-file-based-connectors
It says on that page:
"For all file-based connectors, the payload is a JSON object containing metadata plus an array containing the JSON objects from your stream."
I have the following PHP at the location I have datasift sending data to:
<?php
$myFile = "testFile.txt";
$phpObj = json_decode($_POST['json']);
file_put_contents($myFile,$phpObj);
echo '{ "success": true }';
?>
I know data is being sent, but nothing is being recorded in my text file. It's just blank every time. I have no idea where to go from here unfortunately. Any ideas?
I think you want to get the raw content of the POST, This works for me with both POST and PUT:
$phpObj = json_decode(file_get_contents("php://input"));
$_POST contains the array from x-www-form-urlencoded content, not json.
Hope that points you in the right direction :)
Edit: #user4035 is right... your also trying to save a php object to a file... This is what i would do:
<?php
$jsonString = file_get_contents("php://input");
$myFile = "testFile.txt";
file_put_contents($myFile,$jsonString);
echo '{ "success": true }';
?>
You are trying to save an object, using file_put_contents. While data parameter this function "Can be either a string, an array or a stream resource"
http://php.net/manual/en/function.file-put-contents.php
Look at this example:
<?php
$json = '
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
';
$phpObj = json_decode($json);
var_dump($phpObj);
$myFile = "testFile.txt";
file_put_contents($myFile, $phpObj);
?>
It parses json correctly, but doesn't save anything as well, because php doesn't know, how to serialize $phpObj object.
You need to save raw JSON string:
<?php
$myFile = "testFile.txt";
file_put_contents($myFile,$_POST['json']);
echo '{ "success": true }';
?>
Then you can read the file and parse it if necessary.
I try this method and it works success. So, I share this here.
Source PHP save POST data to file
web_folder/index.php
<?php
$responseBody = file_get_contents('php://input');
$json = json_decode($responseBody);
//return data
echo json_encode($json);
//Save in json file
if($json){
$fp = fopen('results_'.time().'.json', 'w');
fwrite($fp, json_encode($json));
fclose($fp);
}
?>
and run the below code in the terminal for testing, it will create a JSON file with the POST request in the same folder. (Here I used localhost) or you can test using Postman.
curl -i -X PUT -d '{"name":"codehref"}' http://localhost:8888/web_folder/index.php
To bypass the problem I used JSON.stringify.
'formSave' : function(project){
var s = {
"name": project.name,
"data": JSON.stringify(project.data)
};
$.post("sdcform/formSave/" + project.name, s);
}
The 'project' object contains the keys 'name' and 'data' and I only wanted to stringify the data part of it.
This way on the server I can do
$data = isset($_POST['data']) ? json_decode($_POST['data']): new \stdClass();
file_put_contents($filename, json_encode($data, JSON_PRETTY_PRINT));
I could store it directly to the file and save both conversion but I wanted to prettyfy it!
Note: Yes I know! Do not access $_POST directly.
Related
After thorough research I have not been able to find the solution of a simple problem of appending an object to my JSON.
{
"menu": {
"parentmenu1": {
},
"parentmenu1": {
"pm_name": "iceberg 98 ",
"pm_time": "icebeest-98"
}
},
"projectname": "project1",
"place": "gzb",
"firstlogo": "flogo",
"logo": "logo",
"colordirection": "TopLeft",
"color1": "color1",
"color2": "color2",
"fontcolor": "fontcolor"
}
And my PHP code looks like this
<?php
$parentmenu="Sixty";
$childmenu= "hell";
$grandchildmenu= "icebeest";
$parentmenu1="PUSH Approach-98";
$childmenu1= "iceberg 98 ";
$grandchildmenu1= "icebeest-98";
$data = file_get_contents('format.json');
$json_arr = json_decode($data, true);
//$json_arr['menu']=array($parentmenu2);
$parentarray = array('pm_name'=>$childmenu1, 'pm_time'=>$grandchildmenu1);
echo $parentarray['pm_name'];
$json_arr['menu']['parentmenu1'] = $parentarray;
//array_push($json_arr['menu'], $parentarray);
file_put_contents('results_new.json', json_encode($json_arr));
?>
The parentmenu1 gets removed as soon as I re-run the code.
But if I try adding the 2 arrays at once in same file, then it will add.
So please let me find out the way in which I can add data with key to the end of the structure. TIA
I have a large python dictionary, which is sent out as a JSON in a POST request using the py requests library to a web service which accepts incoming JSONs (XAMPP/PHP set up in localhost).
When I receive the transmitted JSON data through the POST request, PHP always gives the output as array, and not as a serialized JSON string.
Secondly, nested elements are missing from the data captured on PHP end.
I am using the following snip to do the job.
Python code :
import json
import requests
dummy_data = {
"param1": "ABCDEF",
"param2": {
"0": "inner_data_0",
"1": "inner_data_1"
},
"param3": {
"very_big_text_key_1": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
},
"very_big_text_key_2": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
}
}
}
headers = {'Content-Type': 'application/json', 'accept' : 'application/json'}
r = requests.post("http://localhost/test/data.php", params = (dummy_data), headers = headers)
print (r.text)
Also tried with :
headers = {'Content-Type': 'application/json'}
Both give the same output as below:
*Hello World!<br/>Printing GET array ...<br/>array(4) {
["param1"]=>
string(6) "ABCDEF"
["param2"]=>
string(1) "1"
["param3"]=>
string(19) "very_big_text_key_2"
["param4"]=>
string(6) "GHIJKL"
}
<br/>Printing POST array ...<br/>array(0) {
}*
I used json and data as parameters to "requests".
r = requests.post("http://localhost/test/data.php", json = (dummy_data), headers = headers)
and
r = requests.post("http://localhost/test/data.php", data = (dummy_data), headers = headers)
Output is as below :
*Hello World!<br/>Printing GET array ...<br/>array(0) {
}
<br/>Printing POST array ...<br/>array(0) {
}*
I am accepting data as follows in PHP code:
<?php
print "Hello World!";
echo "<br/>";
print "Printing GET array ...";
echo "<br/>";
var_dump($_GET);
echo "<br/>";
print "Printing POST array ...";
echo "<br/>";
var_dump($_POST);
?>
The inner text doesn't seem to be appearing in any of the scenarios. I have tried to implement some solutions as suggested by members of stackoverflow. But still i am facing the above mentioned issue.
The problem is now resolved. The resolution happend after consideration of the following points:
JSON passed by Python is not de-serialized by default, by PHP and has to be serialized, after inspection of "Content-type" header.
Once de-serialized, the passed JSON content was then used for further processing.
Hence the key to solve the problem was, to check the content-length, and content-type headers. If content-length was found greater than 0 and content type was application/json, the incoming JSON can be de-serialized using json_decode().
The code snips for PHP and Python, using which the following was accomplished is as below:
On the Python side:
import json
import requests
dummy_data = {
"param1": "ABCDEF",
"param2": {
"0": "inner_data_0",
"1": "inner_data_1"
},
"param3": {
"very_big_text_key_1": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
},
"very_big_text_key_2": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
}
}
}
headers = {'Content-Type': 'application/json'}
r = requests.post("http://localhost/test/data.php", data = json.dumps(dummy_data), headers=headers)
print (r.text)
On the PHP side:
...
if(#$_SERVER["CONTENT_LENGTH"] > 0){
$contentType = $_SERVER["CONTENT_TYPE"];
if($contentType == "application/json"){
$decoded_data = json_decode(file_get_contents("php://input"), true);
}
else{
echo "Incoming data is not a JSON!";
}
return $decoded_data;
}
I've a JSON string, I want to get it in store of Extjs by a PHP url. How to get this string as a JSON from a php file. Something like this:
Extjs file:
PHP file:
The result is blank.
What I do now for this work?
An example of what I believe you mean to do:
$array = array();
$test = '{ "firstName":"John" , "lastName":"Doe" }';
$array[] = json_decode($test);
$test = '{ "firstName":"Jane" , "lastName":"Doe" }';
$array[] = json_decode($test);
$test = '{ "firstName":"Random" , "lastName":"Guy" }';
$array[] = json_decode($test);
print json_encode($array);
exit;
Will give you:
[{"firstName":"John","lastName":"Doe"},{"firstName":"Jane","lastName":"Doe"},{"firstName":"Random","lastName":"Guy"}]
As for the Ajax, maybe this will help - How to get "data" from JQuery Ajax requests, or maybe try the Jquery Ajax documentation.
I'm having difficulties grabbing any of the JSON information from this URL.
I've tried other JSON snippets and they seem to work so I'm not sure if it's the way that the URL is structured or something.
Basic example below.
<?php
$json = file_get_contents('http://nhs-sh.cfpreview.co.uk/api/version/fetchLatestData?dataType=Clinics&versionNumber=-1&uuID=website&dt=');
$obj = json_decode($json);
echo "Body: " . $obj->Body;
?>
The link provided starts with
{ data :
which is valid javascript but invalid json. You can test it on http://jsonlint.com. To fix this we can replace the data with "data" :
$json = file_get_contents('http://nhs-sh.cfpreview.co.uk/api/version/fetchLatestData?dataType=Clinics&versionNumber=-1&uuID=website&dt=');
$obj = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) { //check if there was an error decoding json
$json = '{ "data" :'. substr(trim($json), 8); // replace the first 8-1 characters with { "data" :
$obj = json_decode($json);
}
print_r($obj->data); //show contents of data
Please note that this fix is dependent on the data source e.g. if they change data to dataset. The correct measure would be to ask the developers to fix their json implementation.
I have added new data to my API. I want to return it as plain text
This is the API response PHP returns.
{
"apiVersion":"1.0",
"data":{
"location":"London",:
{
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
I want to return the pressure value on my html page so my users can see the reading. I am having issues displaying it.
This is my PHP api.php
require_once('./includes/config.php');
require_once('./includes/functions.php');
error_reporting(0);
header('Content-Type: text/plain; charset=utf-8;');
$city = $_GET['city'];
if(isset($city)) {
$weather = new Weather($conf['apikey'], $_GET['f']);
$weather_current = $weather->get($city, 0, 0, null, null);
$now = $weather->data(0, $weather_current);
if($now['location'] !== NULL) {
echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }';
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }';
}
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }';
}
In order to fetch data from a JSON source you should parse the data with the json_decode() method. You can then use the second parameter to parse it into an array. If you omit the second parameter you would get an array of objects.
Important: It seems your JSON has a syntax error too. I have added a weather key before the weather information.
$data = '{
"apiVersion":"1.0",
"data":{
"location":"London",
"weather":{ // Notice the new key!
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
}';
$json = json_decode($data, true);
You should then be able to fetch the pressure as an associative array.
$pressure = $json['data']['weather']['pressure']; // Equals: 1021
Hope this can help you, happy coding!
First of all, you need to validate your JSON. It is missing some key things that will keep you from being able to parse it. Use JSONLint to verify your JSON.
After modification the JSON to make it valid I did the following:
$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}';
$obj_style = json_decode($json);
$array_style = json_decode($json, true);
echo $obj_style->data->data->pressure;
echo $array_style['data']['data']['pressure'];
Using json_decode() I was able to setup a way to parse the JSON two ways, once as an object and once as an array (adding the true flag returns the results as an array).
From there all you have to do is drill town to the bits of information that you want to display.