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

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);

Related

how to separate the second comma in a php variable from mysql in html

Sorry if my question is being duplicate because I've tried to find similar questionI've got a data column in MySQL which look something like this :
https://i.stack.imgur.com/3VRI9.png
I've created a form which display the address in html using php.
$pdf_content .= '<div style="padding-left:5%">';
$pdf_content .= $company_name.'<br>';
$pdf_content .= '<div id="errorMessage">'.$address.'<br></div>';
//$pdf_content .= 'Add2,<br>';
//$pdf_content .= 'Add3,<br>';
$pdf_content .= $postcode.'<br>';
$pdf_content .= $state.'<br>';
$pdf_content .= $country.'<br>';
$pdf_content .= $mobile_phone.'<br>';
$pdf_content .= '<b>RE: Quotation for 3<sup>rd</sup> party claim vehicle </b>';
$pdf_content .= '</div><br>';
What I wanted to do now is the address which look something like No.43,Jalan Bandar Bahagia,Taman Pinji Mewah 1 , I wanted to separate the second comma which will look something like this
https://i.stack.imgur.com/0OlG3.png
I've tried but still not working
$pdf_content .= $address.'<br>';
$myList_explode = explode(",",$address);
for($i=0;$i<sizeof($myList_explode);$i++){
echo $myList_explode[$i];
if(($i+1)%2==0){
echo "</br>";
}else{
echo ",";
}
}
Is possible to do it in php while in MySQL it won't be separated?Thanks in advance.
Consume the leading substring before the second occurring comma, then forget it with \K. Then match the second occurring comma and replace it.
Regex prevents having to write a multi-line solution with a loop.
Code: (Demo)
echo preg_replace('~^[^,]*,[^,]*\K,~', '<br>', $address);
Output:
No.43,Jalan Bandar Bahagia<br>Taman Pinji Mewah 1
My pattern bears some similarity to the pattern in this preg_match() call: https://stackoverflow.com/a/65355441/2943403
You can try like this...:
$string = 'No.43,Jalan Bandar Bahagia,Taman Pinji Mewah 1';
echo formatString($string);
// No.43,Jalan Bandar Bahagia
// Taman Pinji Mewah 1
function formatString($inputString) {
$stringToArray = explode(",",$inputString);
$finalString = "";
$count = count($stringToArray) - 1;
foreach($stringToArray as $k => $arr) {
$addon = ",";
if($k == 1) {
$addon = "<br>";
}
if($k == $count) {
$addon = "";
}
$finalString .= $arr.$addon;
}
return $finalString;
}
Basically you create an array from string with explode, loop over it and create a string out of the elements. And since you want to add after second comma, function adds it if $key == 1 (second key).

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 Looping CSV to existing Array [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 6 years ago.
Improve this question
i want to read data from a csv an sort the input to an existing array. Than form the array to a String for, in the next step post it with curl to an existing form. The Problm is i cant get the values from the csv to the string :-( Here's my try:
<?php
$datei = fopen("Testformular.csv", "r");
$data = fgetcsv($datei);
$zeilen = file("Testformular.csv");
$rows= count($zeilen);
$i=1;
while ($i <= $rows){
list($Firma,$Anrede,$Titel,$Vorname,$Nachname,$Strasse,$PLZ,$Telefon,$Fax,$Email,$Nachricht,$CopyFlag) = fgetcsv($fp);
$fields = array(
'tx_btsimplecontact_pi1[name]' => urlencode(""),
'tx_btsimplecontact_pi1[firma]' => urlencode($Firma),
'tx_btsimplecontact_pi1[sex]' => urlencode($Anrede),
'tx_btsimplecontact_pi1[titel]' => urlencode($Titel),
'tx_btsimplecontact_pi1[vorname]' => urlencode($Vorname),
'tx_btsimplecontact_pi1[nachname]' => urlencode($Nachname),
'tx_btsimplecontact_pi1[strasse]' => urlencode($Strasse),
'tx_btsimplecontact_pi1[plz_ort]' => urlencode($PLZ),
'tx_btsimplecontact_pi1[telefon]' => urlencode($Telefon),
'tx_btsimplecontact_pi1[fax]' => urlencode($Fax),
'tx_btsimplecontact_pi1[email]' => urlencode($Email),
'tx_btsimplecontact_pi1[nachricht]' => urlencode($Nachricht),
'tx_btsimplecontact_pi1[copy]' => urlencode($CopyFlag),
'submit' => urlencode("Abschicken")
);
echo "Start at Line:" .$i ."<br/>";
$i++;
foreach($fields as $key=>$value) { $fields_string .= urlencode($key).'='.$value.'&'; }
rtrim($fields_string, '&');
print_r ($string_fields);
echo "Line" .$i ." complete <br/>";
}
Looks to me that you are reading the file into an array three times, once from the existing file pointer using fgetcsv, then you use file() just to count the lines, and then you try to use fgetcsv on a non-existant file pointer.
Here's a quick and dirty edit of your code you can try:
(I'm assuming the CSV-fields are in the order you used in you list()-function.)
<?php
$fp = fopen("Testformular.csv", "r");
$line = 0;
while ( $row = fgetcsv($fp) ) {
// Eliminate the headers
if($line === 0){
$line++;
continue;
}
$output = "";
$output .= 'tx_btsimplecontact_pi1[name]=' . urlencode("");
$output .= '&tx_btsimplecontact_pi1[firma]=' . urlencode($row[0]);
$output .= '&tx_btsimplecontact_pi1[sex]=' . urlencode($row[1]);
$output .= '&tx_btsimplecontact_pi1[titel]=' . urlencode($row[2]);
$output .= '&tx_btsimplecontact_pi1[vorname]=' . urlencode($row[3]);
$output .= '&tx_btsimplecontact_pi1[nachname]=' . urlencode($row[4]);
$output .= '&tx_btsimplecontact_pi1[strasse]=' . urlencode($row[5]);
$output .= '&tx_btsimplecontact_pi1[plz_ort]=' . urlencode($row[6]);
$output .= '&tx_btsimplecontact_pi1[telefon]=' . urlencode($row[7]);
$output .= '&tx_btsimplecontact_pi1[fax]=' . urlencode($row[8]);
$output .= '&tx_btsimplecontact_pi1[email]=' . urlencode($row[9]);
$output .= '&tx_btsimplecontact_pi1[nachricht]=' . urlencode($row[10]);
$output .= '&tx_btsimplecontact_pi1[copy]=' . urlencode($row[11]);
$output .= '&submit=Abschicken';
echo "Line " . $line++ . ": " . $output . PHP_EOL;
}
With this content in the CSV:
Firma,Anrede,Titel,Vorname,Nachname,Strasse,PLZ,Telefon,Fax,Email,Nachricht,Copy‌​Flag
Testfirma1,Herr,Dr.,Vorname1,Name1,Strasse1,11111,12345567,123456,1#keine.de,nac‌​hricht1,1
Gives this result in my terminal:
Line 1: tx_btsimplecontact_pi1[name]=&tx_btsimplecontact_pi1[firma]=Testfirma1&tx_btsimplecontact_pi1[sex]=Herr&tx_btsimplecontact_pi1[titel]=Dr.&tx_btsimplecontact_pi1[vorname]=Vorname1&tx_btsimplecontact_pi1[nachname]=Name1&tx_btsimplecontact_pi1[strasse]=Strasse1&tx_btsimplecontact_pi1[plz_ort]=11111&tx_btsimplecontact_pi1[telefon]=12345567&tx_btsimplecontact_pi1[fax]=123456&tx_btsimplecontact_pi1[email]=1%40keine.de&tx_btsimplecontact_pi1[nachricht]=nac%E2%80%8C%E2%80%8Bhricht1&tx_btsimplecontact_pi1[copy]=1&submit=Abschicken
I put the php in a file (parsefile.php), the CSV in another file (Testformular.csv) and run it in my terminal with php parsefile.php

Error in creating JSON in 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.

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