I want to read the json data on the page http://mattrb.com/txt.txt
For example, let's say I want to get the name "Bulbasaur." I have this code:
<?php
$file = file_get_contents("http://mattrb.com/txt.txt");
$json = json_decode($file);
echo $json->1->name;
?>
This code causes the php to simply not load. Is this because you can't use a number? Next I tried this:
<?php
$file = file_get_contents("http://mattrb.com/txt.txt");
$json = json_decode($file);
$num = 1;
echo $json->$num->name;
?>
This allows the php to load, but still returns nothing. What am I doing wrong?
Your json is invalid. Please check at http://jsonlint.com/.
Also you can access "1" in php like this: echo $json->{1}->name;
Your json file isn't valide You have a comma problem item number 135 try to delete it so you can parse the file .
"135": {, //the problem of your json data is here
"levels": [5, 15],
"probability": 4 "name": "Jolteon",
"attack": 65,
"defense": 60,
"type": "electric",
"moves": [
"tackle",
"thundershock",
"thunder"
],
"curve": 1.6
},
Your json should not contain newline and other invalid characters.
In other words - your json is invalid. json_decode does not work on the file.
$file = file_get_contents("http://mattrb.com/txt.txt");
var_dump(json_decode($file));
// NULL
Related
I’m trying to receive a JSON POST on a payment interface website, but I can’t decode it.
When I print :
echo $_POST;
I get:
Array
I get nothing when I try this:
if ( $_POST ) {
foreach ( $_POST as $key => $value ) {
echo "llave: ".$key."- Valor:".$value."<br />";
}
}
I get nothing when I try this:
$string = $_POST['operation'];
$var = json_decode($string);
echo $var;
I get NULL when I try this:
$data = json_decode( file_get_contents('php://input') );
var_dump( $data->operation );
When I do:
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
I get:
NULL
The JSON format is (according to payment site documentation):
{
"operacion": {
"tok": "[generated token]",
"shop_id": "12313",
"respuesta": "S",
"respuesta_details": "respuesta S",
"extended_respuesta_description": "respuesta extendida",
"moneda": "PYG",
"monto": "10100.00",
"authorization_number": "123456",
"ticket_number": "123456789123456",
"response_code": "00",
"response_description": "Transacción aprobada.",
"security_information": {
"customer_ip": "123.123.123.123",
"card_source": "I",
"card_country": "Croacia",
"version": "0.3",
"risk_index": "0"
}
}
}
The payment site log says everything is OK. What’s the problem?
Try;
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];
From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.
EDIT
Maybe also worth trying to echo the json string from php://input.
echo file_get_contents('php://input');
If you already have your parameters set like $_POST['eg'] for example and you don't wish to change it, simply do it like this:
$_POST = json_decode(file_get_contents('php://input'), true);
This will save you the hassle of changing all $_POST to something else and allow you to still make normal post requests if you wish to take this line out.
It is worth pointing out that if you use json_decode(file_get_contents("php://input")) (as others have mentioned), this will fail if the string is not valid JSON.
This can be simply resolved by first checking if the JSON is valid. i.e.
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params))
$decoded_params = json_decode($json_params);
Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here:
http://ideone.com/va3u8U
Use $HTTP_RAW_POST_DATA instead of $_POST.
It will give you POST data as is.
You will be able to decode it using json_decode() later.
Read the doc:
In general, php://input should be used instead of $HTTP_RAW_POST_DATA.
as in the php Manual
$data = file_get_contents('php://input');
echo $data;
This worked for me.
You can use bellow like..
Post JSON like bellow
Get data from php project user bellow like
// takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json, true);
echo $data['requestCode'];
echo $data['mobileNo'];
echo $data['password'];
Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.
Check whether you are calling the correct ".PHP" file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has "s" (secure) after "http".
Example:
"http://yourdomain.com/read_result.php"
should be
"https://yourdomain.com/read_result.php"
or either way.
add or remove the "s" to match your URL.
If all of the above answers still leads you to NULL input for POST, note that POST/JSON in a localhost setting, it could be because you are not using SSL. (provided you are HTTP with tcp/tls and not udp/quic)
PHP://input will be null on non-https and if you have a redirect in the flow, trying configuring https on your local as standard practice to avoid various issues with security/xss etc
The decoding might be failing (and returning null) because of php magic quotes.
If magic quotes is turned on anything read from _POST/_REQUEST/etc. will have special characters such as "\ that are also part of JSON escaped. Trying to json_decode( this escaped string will fail. It is a deprecated feature still turned on with some hosters.
Workaround that checks if magic quotes are turned on and if so removes them:
function strip_magic_slashes($str) {
return get_magic_quotes_gpc() ? stripslashes($str) : $str;
}
$operation = json_decode(strip_magic_slashes($_POST['operation']));
I got "null" when I tried to retrieve a posted data in PHP
{
"product_id": "48",
"customer_id": "2",
"location": "shelf", // shelf, store <-- comments create php problems
"damage_types":{"Pests":1, "Poke":0, "Tear":0}
// "picture":"jhgkuignk" <-- comments create php problems
}
You should avoid commenting JSON code even if it shows no errors
I'd like to post an answer that also uses curl to get the contents, and mpdf to save the results to a pdf, so you get all the steps of a tipical use case. It's only raw code (so to be adapted to your needs), but it works.
// import mpdf somewhere
require_once dirname(__FILE__) . '/mpdf/vendor/autoload.php';
// get mpdf instance
$mpdf = new \Mpdf\Mpdf();
// src php file
$mysrcfile = 'http://www.somesite.com/somedir/mysrcfile.php';
// where we want to save the pdf
$mydestination = 'http://www.somesite.com/somedir/mypdffile.pdf';
// encode $_POST data to json
$json = json_encode($_POST);
// init curl > pass the url of the php file we want to pass
// data to and then print out to pdf
$ch = curl_init($mysrcfile);
// tell not to echo the results
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );
// set the proper headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]);
// pass the json data to $mysrcfile
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
// exec curl and save results
$html = curl_exec($ch);
curl_close($ch);
// parse html and then save to a pdf file
$mpdf->WriteHTML($html);
$this->mpdf->Output($mydestination, \Mpdf\Output\Destination::FILE);
In $mysrcfile I'll read json data like this (as stated on previous answers):
$data = json_decode(file_get_contents('php://input'));
// (then process it and build the page source)
I'm learning more about parsing JSON in PHP, and I encountered a problem editing a certain file.
I wrote a code that makes it possible to edit only the values I want from a JSON file, and for some reason, when I try to edit the value from "IdList", my code replaces that value without the square brackets, invalidating the JSON structure.
How could I get my code to correctly override this value while keeping it inside the square bracket?
My JSON File
{
"isVisible": false,
"Name": "Lorem ipslum",
"Int": 0,
"IdList": [10, 30, 70],
"UseKeys": true,
}
My PHP code
<?php
$commandline = ($_GET[("string")]);
$json_object = file_get_contents('file.json');
$data = json_decode($json_object, true);
$data['IdList'] = $commandline;
$json_object = json_encode($data, JSON_UNESCAPED_UNICODE);
file_put_contents('file.json', $json_object);
echo('success');
?>
When i try to change IdList to '70, 80, 90' for example, the Json file is saved like this:
"IdList":"70, 80, 90"
It should be saving like this:
"IdList": [70, 80, 90]
When I try to modify the text from the other values, it works normally.
you are setting a string for "IdList"
this would work for you:
$data['IdList'] = array_map('intval', explode(',',$commandline));
You can replace this line:
$data['IdList'] = $commandline;
With:
$data['IdList'] = json_decode('[' . $commandline . ']', true);
I've the following PHP code with a JSON variable...
$route_geometry_json = "{
\"route_geometry\": [
[44.911537, 7.671326],
[44.911481, 7.671462],
[44.911455, 7.671531],
[44.911434, 7.671602],
[44.911358, 7.671859],
[44.911273, 7.672175],
[44.911198, 7.672458],
[44.91113, 7.672617],
[44.911069, 7.67275],
[44.911003, 7.672821],
[44.910945, 7.672881],
[44.910869, 7.672954],
[44.910868, 7.673046],
[44.91091, 7.673109],
[44.91095, 7.67319],
[44.910964, 7.673266],
[44.910958, 7.673407],
[44.910955, 7.6735],
[44.910947, 7.673632],
[44.910922, 7.673871],
[44.910828, 7.674786],
[44.910711, 7.675816],
[44.910606, 7.676364],
[44.910467, 7.676322],
[44.910368, 7.676308],
[44.910051, 7.676253],
[44.9097, 7.676162],
[44.90944, 7.676041],
[44.909297, 7.675958],
[44.909174, 7.67583],
[44.909107, 7.675722],
[44.908993, 7.675583],
[44.908758, 7.675448],
[44.90796, 7.675037]
]
}";
print "Route geometry -->" + json_encode($route_geometry_json);
The print return "0": any suggestion / example?
I'd like also to extract / print the coords couples like
44.908993, 7.675583
44.908758, 7.675448
Any suggestion will be appreciated ...
Thanks
Cesare
Use this code:
$route_geometry = json_decode($route_geometry_json);
foreach ($route_geometry->route_geometry as $value) {
echo $value[0].', '.$value[1].'<br />';
}
You need to print_r(json_decode($route_geometry_json)) it and not json_encode
json_encode is for creating a JSON string. But since you already have a JSON string already, you need to Decode it to make it an Array/Object.
UPDATE
Your requirement
echo "Route geometry -->";
print_r(json_decode($route_geometry_json));
You cannot concat a String and an Object, so you were getting that Parse error.
I want to decode json encoded data, My code output is
[ItemVariant] => [{"VariantID1":"36","VariantID2":"1","RevisionNumber":1,"LineNo":1},{"VariantID1":"47","VariantID2":"44","RevisionNumber":1,"LineNo":1}],
and i am using following code to decode it in controller file in save function
$variantdata = json_decode($this->request->data['ItemVariant']); ,
but not getting expected output,
please suggest me proper solution
There is a unrequired "," at the end. Please remove it.
This should help:
<?php
$str = '[
{
"VariantID1": "36",
"VariantID2": "1",
"RevisionNumber": 1,
"LineNo": 1
},
{
"VariantID1": "47",
"VariantID2": "44",
"RevisionNumber": 1,
"LineNo": 1
}
]';
$json = json_decode($str, true);
print_r($json);
?>
Run the code here:
http://codepad.org/GZcCdkd2
I have a ajax call calling a php file who runs a long php function which returns a JSON encoded array/object. Now I need to send HTML also into the ajax response. I thought about sending the HTML inside the array.
Is that a good practise?
Right now I cannot get it working, I get a NULL as value for that property. Don't know why.
$statHTML = '<table>';
foreach ($toHTML as $key=>$value) {
$statHTML.= '
<tr class="'.$key.'">
<td class="side">'.$value[0].'</td>
<td>'.$value[2].' '.$value[1].'</td>
</tr>';
}
$statHTML.= '</table>';
// echo $statHTML; // - this works
//function return
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => $statHTML
);
return json_encode($answer);
The ajax response from the console before the JSON.parse():
{
"mostSearched": {
"title": "Most serached houses",
"colNames": [21],
"rowNames": [2013],
"rows": [1]
},
"timeOfDay": {
"title": "Time of search",
"colNames": ["07:30"],
"rowNames": ["07:30"],
"rows": [
[1]
]
},
"mostSearchedDays": {
"title": "Most searched days",
"colNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rowNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rows": [
[1, 1, 1, 1, 1, 1, 1]
]
},
"statHTML": null
}
From php.net:
Parameters
value
The value being encoded. Can be any type except a resource.
All string data must be UTF-8 encoded.
So use:
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => utf8_encode($statHTML)
);
return json_encode($answer);
Most likely the build-in JSON parser used by PHP cannot properly parse the HTML, the easiest way to solve the issue is to base64 encode the html on the server, and then decode it on the client, using either the newer atob and btoa base64 methods, or one of the many polyfills out there.
use base64_enccode in this at the time of conversion
$answer = array('statHTML'=>base64_encode('<h1>html in here</h1>'));
echo json_encode($answer);exit;
And at the time of getting response from ajax
atob(response.statHTML);
Hope you understand how it works