The issue is, that I am sending a JSON file in a POST request but i don't know how to get the data from the request itself
Here is the python script that sends the POST request:
import json
import httplib
filepath = 'example.txt'
with open(filepath) as fp:
line = fp.readline()
line2 = fp.readline(9)
jsonbaloo = {}
jsonbaloo["name"] = line
jsonbaloo["score"]= line2
result = json.dumps(jsonbaloo)
def post_dict():
headers = {"Content-type": "application/json", "Accept": "text/plain"}
conn = httplib.HTTPConnection('altrevista.org')
conn.request("POST", "/", result, headers)
post_dict()
I want to get the JSON data server side, so I can put it on an SQL database, but I can't program in PHP.
PHP SCRIPT:
<?php
function detectRequestBody() {
$rawInput = fopen('php://input', 'r');
$tempStream = fopen('php://temp', 'r+');
stream_copy_to_stream($rawInput, $tempStream);
rewind($tempStream);
return $tempStream;
}
?>
conn.read() to get the response back
Since you're writing to a file, you can read from the file using PHP with fopen() or file_get_contents().
Using fopen():
$fileHandle = fopen("path/to/example.txt", "r");
Using file_get_contents():
$fileString = file_get_contents("path/to/example.txt");
You should receive the data using file_get_contents (php://input stream) and convert it to an array using json_decode.
// Retrieve the Post JSON data
$input = file_get_contents('php://input');
// Convert to json to array
$array = json_decode($input, true);
// View the content of the array
print_r($array);
Related
I'm trying to write a json file with data gathered via get requests. The json file is a 2D array of strings, but when the data is written to the file, the nested array is written twice.
<?php
//used for parsing html
include("simple_html_dom.php");
//read the file
$fp = fopen("j.json", "r");
$t = fread($fp, filesize("j.json"));
fclose($fp);
$loaded = json_decode($t);
//print the loaded array
print_r($loaded);
//gathering the data
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo1 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
$data = file_get_html($url)->find("span[class=ora] b", 0)->plaintext;
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo2 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo3 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
//adding the new data to the array
array_push($loaded, array($prezzo1, $prezzo2, $prezzo3, $data));
//the new json string is parsed and ready to be written
$s = json_encode($loaded);
//printing stuff to ensure the data is correct
echo "<br>".$s.", type=".gettype($s)."<br>";
print_r($loaded);
//write the new json string to the same file
$fp = fopen("j.json", "w");
fwrite($fp, $s);
fclose($fp);
?>
j.json before the script runs:
[]
What the script prints:
Array ( )
[["128,54","128,54","128,54","30\/12"]], type=string
Array ( [0] => Array ( [0] => 128,54 [1] => 128,54 [2] => 128,54 [3] => 30/12 ) )
j.json after the script:
[["128,54","128,54","128,54","30\/12"],["128,54","128,54","128,54","30\/12"]]
I tried opening the file like this: $fp = fopen("j.json", "r+"); and at the and i changed the script:
$s = "\"".json_encode($loaded)."\"";
echo "<br>".$s.", type=".gettype($s)."<br>";
print_r($loaded);
fwrite($fp, $s);
fclose($fp);
And I found out that a null is being written too:
[]"[["128,54","128,54","128,54","30\/12"]]""null"
The browser sends two requests when visiting a url, a request to the php file and another request to /favicon.ico. The second request is send to check if the site has a favicon. This second requests causes the script to execute twice.
The request for the favicon can be prevented by following the steps described here: https://stackoverflow.com/a/38917888/6310593
Hi Guys I have a JSON data I need to convert this data Treeview a json data url: http://torrent2dl.ml/json.php
recovered state = http://torrent2dl.ml/json.php?tree
I tried to do http://torrent2dl.ml/hedef.php
how to convert this data a php function or code ?
json_decode($jsonObject, true);
Use json_decode() :
<?php
$url = 'http://torrent2dl.ml/json.php';
$JSON = file_get_contents($url);
// echo the JSON (you can echo this to JavaScript to use it there)
echo $JSON;
// You can decode it to process it in PHP
$data = json_decode($JSON);
var_dump($data);
?>
Source : https://stackoverflow.com/a/8344667/4652564
I have a JSON file badly formatted (doc1.json):
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192}
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472}
{...}{...}
And I have to change it in this:
{"u":[
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192},
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472},
{...},{...}
]}
Can I do this in a PHP file?
//Get the contents of file
$fileStr = file_get_contents(filelocation);
//Make proper json
$fileStr = str_replace('}{', '},{', $fileStr);
//Create new json
$fileStr = '{"u":[' . $fileStr . ']}';
//Insert the new string into the file
file_put_contents(filelocation, $fileStr);
I would build the data structure you want from the file:
$file_path = '/path/to/file';
$array_from_file = file($file_path);
// set up object container
$obj = new StdClass;
$obj->u = array();
// iterate through lines from file
// load data into object container
foreach($array_from_file as $json) {
$line_obj = json_decode($json);
if(is_null($line_obj)) {
throw new Exception('We have some bad JSON here.');
} else {
$obj->u[] = $line_obj;
}
}
// encode to JSON
$json = json_encode($obj);
// overwrite existing file
// use 'w' mode to truncate file and open for writing
$fh = fopen($file_path, 'w');
// write JSON to file
$bytes_written = fwrite($fh, $json);
fclose($fh);
This assumes each of the JSON object repsentations in your original file are on a separate line.
I prefer this approach over string manipulation, as you can then have built in checks where you are decoding JSON to see if the input is valid JSON format that can be de-serialized. If the script operates successfully, this guarantees that your output will be able to be de-serialized by the caller to the script.
I've got a really weird problem and I can't figure out why.
The situation is quite simple. My Android app uploads JSON data to a php script on my server. Right now I am trying to parse the data.
This is the JSON-Array passed to the script (via httpPost.setEntity ()):
[{"friends_with_accepted":"false","friends_with_synced":"false","friends_with_second_id":"5","friends_with_first_id":"6"}]
This is the php script:
<?php
// array for JSON response
$response = array();
$json = file_get_contents ('php://input');
$jsonArray = json_decode ($json, true);
foreach ($jsonArray as $jsonObject) {
$firstId = $jsonObject['friends_with_first_id'];
$accepted = $jsonObject ['friends_with_accepted'];
$secondId = $jsonObject ['friends_with_second_id'];
$synced = $jsonObject ['friends_with_synced'];
echo "accepted: ".$accepted."synced: ".$synced;
} ?>
And this is the response I get from the script:
accepted: synced: false
Why is the "synced" property correctly passed, but not the "accepted" property??
I can't see the difference. Btw, firstId and secondId are parsed correctly as well.
Okay, i just found the problem:
Instead of
$accepted = $jsonObject ['friends_with_accepted'];
I deleted the space between jsonObject and the bracket
$accepted = $jsonObject['friends_with_accepted'];
Im try export json result to csv and save data as file, im try with something like this
$getFile = file_get_contents('JSON_URL');
$json_obj = json_decode($getFile);
$fp = fopen('/home/xxxx/public_html/xxxx/api/export/tmp/file.csv', 'w');
foreach ($json_obj as $row) {
fputcsv($fp, $row);
}
fclose($fp);
but seems not working
Here's an example json format for link above
[
{key:value,key:value...}
...]
in order for your code to work as expected, try decoding the json object as an associative array. This is done by passing a boolean true to the 2nd param of json_decode
$json_obj = json_decode($getFile, true);