Error in creating JSON in PHP - php

I'm very new to PHP and JSON, so I hope you'll excuse my (probably) stupid question.
I'm trying to create a new JSON with fundamental information for my needings, using the information returned by Google Maps API.
Here's the code:
<?php
/**
* Created by PhpStorm.
* User: biagiomontesano
* Date: 22/10/15
* Time: 18:16
*/
function selectLongestSteps($steps_txt, $min_meters)
{
$steps = JSON.parse($steps_txt);
//$steps = json_decode($steps_txt, true);
//$steps = $steps_txt;
echo 'Num of steps: ' . count($steps[0]);
}
function createJsonFromResponse($response_json)
{
// output json
$output_json = '[';
// number of steps
$num_steps = count($response_json['routes'][0]['legs'][0]['steps']);
//echo $num_steps;
// fill the json
for($i = 0; $i<$num_steps; $i++)
{
// start parenthesis
$output_json .= '{';
// start latitude
$output_json .= '"start_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lat'] . ',';
// start longitude
$output_json .= '"start_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lng'] . ',';
// end latitude
$output_json .= '"end_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lat'] . ',';
// end latitude
$output_json .= '"end_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lng'] . ',';
// step length
$output_json .= '"step_length":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['distance']['value']. ',';
// html instruction
$output_json .= '"instruction":"' . $response_json['routes'][0]['legs'][0]['steps'][$i]['html_instructions'] . '"';
// closure parenthesis
$output_json .= '}';
// insert comma if required
if($i != $num_steps-1)
$output_json .= ',';
}
$output_json .= ']';
return $output_json;
}
function get_driving_information($start, $finish)
{
if (strcmp($start, $finish) != 0) {
$start = urlencode($start);
$finish = urlencode($finish);
$url = 'http://maps.googleapis.com/maps/api/directions/json?origin=' . $start . '&destination=' . $finish . '&sensor=false';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return $resp;
}
else
return null;
}
try
{
$info = get_driving_information('via Tiburtina 538, Roma', 'via Ariosto 25, Roma');
$steps = null;
if(!$info)
echo 'No info';
else
$steps = createJsonFromResponse($info);
selectLongestSteps($steps, 200);
//echo $steps;
}
catch(Exception $e)
{
echo 'Caught exception: '.$e->getMessage()."\n";
}
As a test, I asked my function selectLongestSteps to display the number of elements in the JSON.
As you see, I tried to initialise variable $steps in 3 different ways: the last two return a wrong results (0 or 1, while result should be 18).
The first one, that I found on web, returns the following error:
Notice: Use of undefined constant JSON - assumed 'JSON' in /Applications/XAMPP/xamppfiles/htdocs/prova_php/create_json.php on line 11
Fatal error: Call to undefined function parse() in /Applications/XAMPP/xamppfiles/htdocs/prova_php/create_json.php on line 11
I suspect the problem is in creating JSON inside the other function.
Can you help?
Thanks

The problem is this line:
$steps = JSON.parse($steps_txt);
JSON.parse() ist a JavaScript function. You need something like this in PHP
$steps = json_decode($steps_txt);
http://php.net/manual/en/function.json-decode.php

PHP has in-built function to change array to json and vice-verse.
json_encode($array) will give json form of array.
json_decode($json, true) will give your array back from json. If you didn't give true as your second param, you will be getting an object instead of an array.

Related

Trying to find a way to take a series of values in a json array and add them to an int

Here is my PHP function that grabs data from inputs on the page.
function getCounts($selection, $srch) {
$loadjson = file_get_contents('data.json');
$jsondata = json_decode($loadjson);
$total = 0;
foreach ($jsondata as $list) {
if ($list->$selection == $srch) {
$total .= $list->TOTAL
}
}
echo 'Total - ' . $total . '<br>' . '<br>';
}
I know the issue is with the line "$total .= $list->TOTAL" but I cannot figure out how to take the value that "$list->TOTAL" gets and add it to an integer. I have tested and if I do "echo $list->TOTAL . ','" instead of "$total .= $list->TOTAL" the function spits out a list of all the numbers that are in the JSON data I simply cannot figure out how to get the numbers into an integr and added into one number.
Can someone point me in the right direction?

PHP: can't decode JSON from string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I wrote this function to build a JSON-style string:
function createJsonFromResponse($response_json)
{
// output json
$output_json = '[';
// number of steps
$num_steps = count($response_json['routes'][0]['legs'][0]['steps']);
//echo $num_steps;
// fill the json
for($i = 0; $i<$num_steps; $i++)
{
// start parenthesis
$output_json .= '{';
// start latitude
$output_json .= '"start_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lat'] . ',';
// start longitude
$output_json .= '"start_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lng'] . ',';
// end latitude
$output_json .= '"end_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lat'] . ',';
// end latitude
$output_json .= '"end_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lng'] . ',';
// step length
$output_json .= '"step_length":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['distance']['value'] . ',';
// html instruction
$output_json .= '"instruction":"' . $response_json['routes'][0]['legs'][0]['steps'][$i]['html_instructions'] . '"';
// closure parenthesis
$output_json .= '}';
// insert comma if required
if($i != $num_steps-1)
$output_json .= ',';
}
$output_json .= ']';
return $output_json;
}
Then, I gave the output string from this function to another one. This second function performs this simple action:
$steps_dec = json_decode($steps_txt,true);
where $steps_txt is the string I produced previously.
Anyway, I testes that the output of json_decode is NULL, while everything work if, in the function producing string, I comment the line adding string field.
It seems to like only numeric field.
can you spot my error?
thanks.
Simplest json in php
$myJson = array('numbers' => array(1, 2, 3));
echo json_encode($myJson);

Getting Max Value from an array

Hi I am trying to use an api from postcodeanywhere that calcuates the total travel time and distance for a particular journey, and I have got it working using the following code:
//Build URL Request
$url = "http://services.postcodeanywhere.co.uk/DistancesAndDirections/Interactive/Directions/v2.00/xmla.ws?";
$url .= "&Key=" . urlencode($Key);
$url .= "&Start=" . urlencode($Start);
$url .= "&Finish=" . urlencode($Finish);
$url .= "&DistanceType=" . urlencode($DistanceType);
//Make the request to Postcode Anywhere and parse the XML returned
$file = simplexml_load_file($url);
//Check for an error, if there is one then throw an exception
if ($file->Columns->Column->attributes()->Name == "Error")
{
throw new Exception("[ID] " . $file->Rows->Row->attributes()->Error . " [DESCRIPTION] " . $file->Rows->Row->attributes()->Description . " [CAUSE] " . $file->Rows->Row->attributes()->Cause . " [RESOLUTION] " . $file->Rows->Row->attributes()->Resolution);
}
//Copy the data
if ( !empty($file->Rows) )
{
foreach ($file->Rows->Row as $item)
{
$Data[] = array('SegmentNumber'=>$item->attributes()->SegmentNumber,'StepNumber'=>$item->attributes()->StepNumber,'Action'=>$item->attributes()->Action,'Description'=>$item->attributes()->Description,'Road'=>$item->attributes()->Road,'StepTime'=>$item->attributes()->StepTime,'StepDistance'=>$item->attributes()->StepDistance,'TotalTime'=>$item->attributes()->TotalTime,'TotalDistance'=>$item->attributes()->TotalDistance);
$TotalDistance = ($item["TotalDistance"] * 0.000621371192);
echo $TotalDistance."<br>";
Which results in the following screenshot
The problem I am having is that the echo shows that it is displaying distance for each journey step, whereas I just want the max value.
I have tried $TotalDistance = max($item["TotalDistance"]). only to get the following error:
max(): When only one parameter is given, it must be an array
Any help would be appreciated.
You can get the max value:
$value = max($array);
What you could do is put the total distance into an array first, then grab the max. Like this:
$distance_array = new array();
foreach ($file->Rows->Row as $item)
{
$Data[] = array('SegmentNumber'=>$item->attributes()->SegmentNumber,'StepNumber'=>$item->attributes()->StepNumber,'Action'=>$item->attributes()->Action,'Description'=>$item->attributes()->Description,'Road'=>$item->attributes()->Road,'StepTime'=>$item->attributes()->StepTime,'StepDistance'=>$item->attributes()->StepDistance,'TotalTime'=>$item->attributes()->TotalTime,'TotalDistance'=>$item->attributes()->TotalDistance);
$TotalDistance = ($item["TotalDistance"] * 0.000621371192);
array_push($distance_array, $TotalDistance); //add the distance to an array
}
echo max($distance_array);
http://php.net/manual/en/function.array-push.php
http://php.net/manual/en/function.max.php

Convert Json to Html - below json i will get from server, i want to display it as html table

{"status":"OK","data":{"train_number":"11111","chart_prepared":false,"pnr_number":"4259444444","train_name":"AAA","travel_date":{"timestamp":1394841600,"date":"10-4-2014"},"from":{"code":"ABC","name":"CITYJUNCTION","time":"20:30"},"to":{"code":"XYZ","name":"TTR","time":"05:35"},"alight":{"code":"DDD","name":"TTR","time":"05:35"},"board":{"code":"ABC","name":"FFF","time":"20:30","timestamp":1394895600},"class":"SL","passenger":[{"seat_number":"S7 , 11,GN","status":"CNF"},{"seat_number":"S7 , 06,GN","status":"CNF"}]}}
You'll need to use json_decode to convert the json string to an object or associative array, you may then iterate over the result. Remember to use htmlspecialchars or htmlentities to escape the data.
This should help get you started:
function table_encode(array $array) {
$buffer = '<table border="1"><thead>';
foreach (array_keys($array) as $header) {
$buffer .= '<th style="text-align:left">' . htmlspecialchars($header) . '</th>';
}
$buffer .= '</thead><tbody><tr>';
foreach ($array as $value) {
$buffer .= '<td>';
if (is_array($value)) {
$buffer .= table_encode($value);
} else {
$buffer .= htmlspecialchars($value);
}
$buffer .= '</td>';
}
$buffer .= '</tbody></table>';
return $buffer;
}
$json = '{"status":"OK","data":{"train_number":"11111","chart_prepared":false,"pnr_number":"4259444444","train_name":"AAA","travel_date":{"timestamp":1394841600,"date":"10-4-2014"},"from":{"code":"ABC","name":"CITYJUNCTION","time":"20:30"},"to":{"code":"XYZ","name":"TTR","time":"05:35"},"alight":{"code":"DDD","name":"TTR","time":"05:35"},"board":{"code":"ABC","name":"FFF","time":"20:30","timestamp":1394895600},"class":"SL","passenger":[{"seat_number":"S7 , 11,GN","status":"CNF"},{"seat_number":"S7 , 06,GN","status":"CNF"}]}}';
$json = json_decode($json, true);
$html = table_encode($json['data']);
echo $html;
$json = json_decode($array);//Decode Json
eccho($json);
function eccho($json){
foreach ($json as $file)
{
if(is_array($file))
return eccho($json);
else
echo "<tr>";
echo "<td> $file </td>";
echo "</tr>";
}
}
maybe this is useful for you...
you can't convert direct in to html..
use can use json_decode() function to convert it in to php array like follow or else use parse the json in jquery/javascript..
$var = '{"status":"OK","data":{"train_number":"11111","chart_prepared":false,"pnr_number":"4259444444","train_name":"AAA","travel_date":{"timestamp":1394841600,"date":"10-4-2014"},"from":{"code":"ABC","name":"CITYJUNCTION","time":"20:30"},"to":{"code":"XYZ","name":"TTR","time":"05:35"},"alight":{"code":"DDD","name":"TTR","time":"05:35"},"board":{"code":"ABC","name":"FFF","time":"20:30","timestamp":1394895600},"class":"SL","passenger":[{"seat_number":"S7 , 11,GN","status":"CNF"},{"seat_number":"S7 , 06,GN","status":"CNF"}]}}';
$ab = json_decode($var,true);
print_r($ab); // here u will get your json data in php array. so now you can print it in html based on your requirements..
hope it will help you
If your get response form server through AJAX then use
var json = '{"status":"OK","data":{"train_number":"11111","chart_prepared":false,"pnr_number":"4259444444","train_name":"AAA","travel_date":{"timestamp":1394841600,"date":"10-4-2014"},"from":{"code":"ABC","name":"CITYJUNCTION","time":"20:30"},"to":{"code":"XYZ","name":"TTR","time":"05:35"},"alight":{"code":"DDD","name":"TTR","time":"05:35"},"board":{"code":"ABC","name":"FFF","time":"20:30","timestamp":1394895600},"class":"SL","passenger":[{"seat_number":"S7 , 11,GN","status":"CNF"},{"seat_number":"S7 , 06,GN","status":"CNF"}]}}';
obj = JSON.parse(json);
or use
data = eval( '(' + json + ')');
Now you can access
var status = data.status;
and you can easily display display data in html.

CSV to JSON with PHP?

I need to convert a CSV file to JSON on the server using PHP. I am using this script which works:
function csvToJSON($csv) {
$rows = explode("\n", $csv);
$i = 0;
$len = count($rows);
$json = "{\n" . ' "data" : [';
foreach ($rows as $row) {
$cols = explode(',', $row);
$json .= "\n {\n";
$json .= ' "var0" : "' . $cols[0] . "\",\n";
$json .= ' "var1" : "' . $cols[1] . "\",\n";
$json .= ' "var2" : "' . $cols[2] . "\",\n";
$json .= ' "var3" : "' . $cols[3] . "\",\n";
$json .= ' "var4" : "' . $cols[4] . "\",\n";
$json .= ' "var5" : "' . $cols[5] . "\",\n";
$json .= ' "var6" : "' . $cols[6] . "\",\n";
$json .= ' "var7" : "' . $cols[7] . "\",\n";
$json .= ' "var8" : "' . $cols[8] . "\",\n";
$json .= ' "var9" : "' . $cols[9] . "\",\n";
$json .= ' "var10" : "' . $cols[10] . '"';
$json .= "\n }";
if ($i !== $len - 1) {
$json .= ',';
}
$i++;
}
$json .= "\n ]\n}";
return $json;
}
$json = csvToJSON($csv);
$json = preg_replace('/[ \n]/', '', $json);
header('Content-Type: text/plain');
header('Cache-Control: no-cache');
echo $json;
The $csv variable is a string resulting from a cURL request which returns the CSV content.
I am sure this is not the most efficient PHP code to do it because I am a beginner developer and my knowledge of PHP is low. Is there a better, more efficient way to convert CSV to JSON using PHP?
Thanks in advance.
Note. I am aware that I am adding whitespace and then removing it, I do this so I can have the option to return "readable" JSON by removing the line $json = preg_replace('/[ \n]/', '', $json); for testing purposes.
Edit. Thanks for your replies, based on them the new code is like this:
function csvToJson($csv) {
$rows = explode("\n", trim($csv));
$csvarr = array_map(function ($row) {
$keys = array('var0','var1','var2','var3','var4','var5','var6','var7','var8','var9','var10');
return array_combine($keys, str_getcsv($row));
}, $rows);
$json = json_encode($csvarr);
return $json;
}
$json = csvToJson($csv);
header('Content-Type: application/json');
header('Cache-Control: no-cache');
echo $json;
Well there is the json_encode() function, which you should use rather than building up the JSON output yourself. And there is also a function str_getcsv() for parsing CSV:
$array = array_map("str_getcsv", explode("\n", $csv));
print json_encode($array);
You must however adapt the $array if you want the JSON output to hold named fields.
I modified the answer in the question to use the first line of the CSV for the array keys. This has the advantage of not having to hard-code the keys in the function allowing it to work for any CSV with column headers and any number of columns.
Here is my modified version:
function csvToJson($csv) {
$rows = explode("\n", trim($csv));
$data = array_slice($rows, 1);
$keys = array_fill(0, count($data), $rows[0]);
$json = array_map(function ($row, $key) {
return array_combine(str_getcsv($key), str_getcsv($row));
}, $data, $keys);
return json_encode($json);
}
None of these answers work with multiline cells, because they all assume a row ends with '\n'. The builtin fgetcsv function understands that multiline cells are enclosed in " so it doesn't run into the same problem. The code below instead of relying on '\n' to find each row of a csv lets fgetcsv go row by row and prep our output.
function csv_to_json($file){
$columns = fgetcsv($file); // first lets get the keys.
$output = array(); // we will build out an array of arrays here.
while(!feof($file)){ // until we get to the end of file, we'll pull in a new line
$line = fgetcsv($file); // gets the next line
$lineObject = array(); // we build out each line with our $columns keys
foreach($columns as $key => $value){
$lineObject[$value] = $line[$key];
}
array_push($output, $lineObject);
}
return json_encode($output); // encode it as json before sending it back
}
Some tips...
If you have URL opening enabled for fopen() and wrappers, you can use fgetscsv().
You can build an array of the CSV, and then convert it with PHP's native json_encode().
The correct mime type for JSON is application/json.
You could probably reduce the overhead by removing all the spaces and \n's. But that's in your note.
You could increase the performance by skipping the preg_replace and passing a boolean that would turn it on and off.
Other than that, the variable unrolling of your var[1-10] actually is good, as long as there are always ten varaibles.
The explode and the foreach approach are just fine.
I recommend using Coseva (a csv parsing library) and using the built in toJSON() method.
<?php
// load
require('../src/CSV.php');
// read
$csv = new Coseva\CSV('path/to/my_csv.csv');
// parse
$csv->parse();
// disco
echo $csv->toJSON();

Categories