I really need your help.
I´m using this code to write into text file from form:
$data = $_POST['jmeno'] . "\t" . $_POST['prijmeni'] . "\t" . $_POST['ulice'] . "\t" . $_POST['cislo_popisne'] . "\t" . $_POST['mesto'] . "\t" . $_POST['psc']. "\n";
$myfile = fopen("zakaznici.txt", "ab") or die("Unable to open file!");
fwrite($myfile, $data);
fclose($myfile);
This is my code to read from text file:
$filename = 'zakaznici.txt';
$handle = fopen($filename, 'r');
$datain = fread($handle, filesize($filename));
$array = explode("\t",$datain);
echo "<table class='styl'><th>Jméno</th><th>Příjmení</th><th>Ulice</th><th>Číslo popisné</th><th>Město</th><th>PSČ</th><tr>".implode("</tr><tr>",array_map(function($a) {return "<td>".implode("</td><td>",explode("\t",trim($a)))."</td>";},explode("\n",$datain)))."</tr></table>";
And in table it looks like this:
Table
Any advice how to sort it alphabetically? I mean for example, when I choose "Jmeno" in select option a hit "Odeslat", I will get sorted table by column "Jmeno" like this (ivana, stepan, tomas).
When using the explode function, it puts all the values in an array. What you can do before echoing the data, is sorting the array.
https://secure.php.net/manual/en/function.sort.php
$data = "atest\tctest\tptest\tqtest\tbtest\tltest";
$values = explode("\t", $data);
sort($values, SORT_STRING);
echo "<table class='styl'><th>Jméno</th><th>Příjmení</th><th>Ulice</th><th>Číslo popisné</th><th>Město</th><th>PSČ</th>";
echo "<tr>";
foreach($values as $value)
{
echo "<td>" . $value . "</td>";
}
echo "</tr></table>";
Result:
Jméno Příjmení Ulice Číslo popisné Město PSČ
atest btest ctest ltest ptest qtest
I´m getting this.
table
Really don´t know how to do it.
Related
I'm just getting into php, html etc and am trying to resolve an issue at work. Please be patient with my lack of experience.
I have a csv file, TEST2.csv. it is as follows advisor,guest,stockNumber,part,qty,partnote1,partnote2,status that I am putting on a webpage so that our staff can select their advisor number and see the status of their parts. The report we export from our system is in csv and has columns that I do not want to show on this report.
(before I hear I should learn another format to display this, I know, Im under a time constraint and need something quick and rudimentary for now)
Everything works well but it does not show column 7, only up to 4. I want it to skip 5,6 Here's the monster i've created:
<table id="demo">
<tbody>
<?php
$fp = fopen ( "TEST2.csv" , "r" );
$wantedColumns = array(0,1,2,3,4,7);
while (( $data = fgetcsv ( $fp , 1000 , "," )) !== FALSE ) {
$i = 0;
echo "<tr>";
foreach($data as $row) {
if (!in_array($i,$wantedColumns)) continue;
echo "<td>" . $row . "</td>";
$i++ ;
}
echo "/<tr>";
}
fclose ( $fp );
?>
`
Any help would be greatly appreciated!
Using simple array syntax with [index] your code will be:
$fp = fopen ( "TEST2.csv" , "r" );
while (( $data = fgetcsv ( $fp , 1000 , "," )) !== FALSE ) {
echo "<tr>";
echo "<td>" . $data[0] . "</td>";
echo "<td>" . $data[1] . "</td>";
echo "<td>" . $data[2] . "</td>";
echo "<td>" . $data[3] . "</td>";
echo "<td>" . $data[4] . "</td>";
echo "<td>" . $data[7] . "</td>";
echo "</tr>";
}
fclose ( $fp );
I am trying to set location markers. The code below is not looping through the results and displays only the first row. I tested the query and result outside of Google Maps and it work.
var addresses = [
<?php
while($row = mysql_fetch_array($results)) {
echo '"'.$row['company'].', '. $row['address'].', ' . $row['city'] . ', ' . $row['state'] . ', ' . $row['zip'] .'",';
}
?>
];
This is what you should do:
<?php
...
$array = array();
while ($row = mysql_fetch_assoc($results)) {
$array[] = array(
'company'=>$row['company'],
'address'=>$row['address'],
'lat'=>$row['latitude'],
'lng'=>$row['longitude'],
); // add what ever cels you need
}
$json_string = json_encode($array);
echo 'var addresses=' . $json_string . ';';
...
?>
If you keep having problems, please post the javascript part of the code; this is just the part where you print an object (or array) in a format that javascript can read.
I'm trying to do something very basic but I can't figure out how.
basically i'm trying to convert the mysql result ($row) into the following format (literal strings):
"0784562627828" => "James",
"0786636363663" => "David",
I have all the data stored in the database and I can get them echoed on my page like so:
$phone = $row['phone'];
$name = $row['name'];
$list .=''.$phone.'';
echo $list;
could someone please advise on this?
Thanks
Just assign them inside an array like you normally would:
$array = array();
while(your fetch here) {
$array[$row['phone']] = $row['name'];
}
To check its contents, you can use var_dump($array) or print_r($array)
Or just straight up show them, like the one you formatted:
while(your fetch here) {
echo '"' . $row['phone'] . '"' . ' => ' . '"' . $row['name'] . '"' . '<br/>';
}
you mean something like this?
$list = array();
$list[$phone] = $name;
Can you do something like
$list = [];
foreach($rows as $row) {
$list[$row['phone']] = $row['name'];
}
I am a newbie to php and have been searching tirelessly for a solution to this problem (i'll bet its a super simple solve too *sigh).
I am importing a .csv feed from a google doc. It is pulling in 2 columns, one for "name" and the other "location". I would like to remove duplicate "locations". since i am using fgetcsv, my understanding is that it is already sorting the data into an array. Ideally, it would omit the "location" duplicates so that the "names" look as though they are listed under the "location" they correspond to.
Here is what i have:
$url = "https://docs.google.com/spreadsheet/pub?key=0AsMT_AMlRR9TdE44QmlGd1FwTmhRRkFHMzFTeTZhS3c&output=csv";
$handle = fopen($url, "r");
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
echo "<li>\n";
echo $data[1];
echo "<br/>\n";
echo $data[2];
echo "</li>\n";
}
fclose($handle);
ideally i would be able to use something like this:
$url = "https://docs.google.com/spreadsheet/pub?key=0AsMT_AMlRR9TdE44QmlGd1FwTmhRRkFHMzFTeTZhS3c&output=csv";
$handle = fopen($url, "r");
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
echo "<li>\n";
echo array_unique($data[1]);
echo "<br/>\n";
echo $data[2];
echo "</li>\n";
}
fclose($handle);
Many thanks in advance for any help! :o)
This may work, assuming that the items in the array are grouped by location. It stores the last data item (location) and compares whether each item has that location. If it does, it prints it, otherwise it creates a new list item with the new location, and then prints the name underneath (I haven't tested it though):
$url = "the-url-to-my-csv-feed";
$handle = fopen($url, "r");
$lastdata = '';
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
if ($lastdata == '') {
echo "<li><strong>" . $data[1] . "</strong>\n";
echo "<br/>\n";
$lastdata = $data[1];
}
if ($lastdata != $data[1]) {
echo "</li>\n";
echo "<li><strong>" . $data[1] . "</strong>\n";
echo "<br/>\n";
$lastdata == $data[1];
}
echo $data[2] . "<br/>\n";
}
fclose($handle);
<? //PHP 5.4+
$url = 'url to your csv feed';
//Group people by same location first,
//not assuming csv is already sorted.
$namesByLocations = [];
//Because we're using \SplFileObject, when the reference goes out
//of scope at the end of the loop, the file pointer is never
//left open. This is true even if an exception is thrown
//in the middle of looping.
foreach(
\call_user_function(static function() use ($url){
$file = new \SplFileObject($url);
$file->setFlags(\SplFileObject::READ_CSV);
return $file;
})
as $array
){
//$array[1] is assumed to be location string
//$array[2] is assumed to be a name that is there.
$namesByLocations[$array[1]][] = $array[2];
}
foreach($namesByLocations as $location => $names){
//Protect against injection flaws,
//escape to destination's context. (html this time)
echo '<strong>' . \htmlspecialchars($location) . '</strong>';
echo '<ul>';
foreach($names as $name){
echo '<li>' . \htmlspecialchars($name) . '</li>';
}
echo '</ul>';
}
?>
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();