I have an HTML form, like survey and have a PHP file with this code
<?php
$fieldA = $_POST["prezime"];
$fieldB = $_POST["ime"];
$fieldC = $_POST["datumrodjenja"];
$fieldD = $_POST["mestorodjenja"];
$fieldE = $_POST["rod"];
$fieldF = $_POST["prebivaliste"];
$fieldG = $_POST["brojpasosa"];
$fieldH = $_POST["izdatod"];
$fieldI = $_POST["vazido"];
$fieldJ = $_POST["profesija"];
$fieldK = $_POST["zanimanje"];
$fieldL = $_POST["fiksni"];
$fieldM = $_POST["mobilni"];
$fieldN = $_POST["email"];
$fieldO = $_POST["napomena"];
$keys = array($fieldA,$fieldB,$fieldC,$fieldD,$fieldE,$fieldF,$fieldG,$fieldH,$fieldI,$fieldJ,$fieldK,$fieldL,$fieldM,$fieldN,$fieldO); //THIS IS WHERE YOU PUT THE FORM ELEMENTS ex: array('$fieldA','$fieldB',etc)
$csv_line = $keys;
foreach( $keys as $key ){
array_push($csv_line,'' . $_GET[$key]);
}
$fname = 'prijave.csv'; //NAME OF THE FILE
$csv_line = implode(',',$csv_line);
if(!file_exists($fname)){$csv_line = $csv_line."\r\n" ;}
$fcon = fopen($fname,'a');
$fcontent = $csv_line;
fwrite($fcon,$csv_line);
fclose($fcon);
?>
The problem with this code is that it creates .csv file, but with no more than 2 rows. When 2 rows are filled with informations from the form, no more collecting.
And the second question, how to allow š ć đ č letters to be collected from the form via this script? Thank you!
I had a similar requirement for a project I was working on. I came up with this small function to write an array to a CSV file ( Comma Delimited ).
I used the fputcsv() function which is pretty handy.
The function accepts 2 arguments, the array name as well as the name you would like the CSV file to be called. Using the fopen, i open the an empty file in the directory where I want to save the CSV file.
I set the header if I need one and write that out to the file.
I then loop through the array and output each element and delimit it by a ",".
Once done, I close the file.
I understand this may not answer your full question, but I believe this will help you in someway.
If your array looks like the same format as the one below, Then the function I have provided will work.
Array
Array
(
[0] => John
[1] => Doe
[2] => England
[3] => Somewhere
[4] => Something
[5] => UK
[6] => Foo
[7] => Bar
[8] => Yes
[9] => Developer
[10] => Stack Overflow
[11] => No
[12] => 0123456778
[13] => johndoe#gmail.com
[14] => Smith
)
Function
<?php
//Change these strings back to what you need
$fieldA = "John";
$fieldB = "Doe";
$fieldC = "England";
$fieldD = "Somewhere";
$fieldE = "Something";
$fieldF = "UK";
$fieldG = "Foo";
$fieldH = "Bar";
$fieldI = "Yes";
$fieldJ = "Developer";
$fieldK = "Stack Overflow";
$fieldL = "No";
$fieldM = "0123456778";
$fieldN = "johndoe#gmail.com";
$fieldO = "Smith";
$array = array( $fieldA,$fieldB,$fieldC,$fieldD,$fieldE,$fieldF,$fieldG,$fieldH,$fieldI,$fieldJ,$fieldK,$fieldL,$fieldM,$fieldN,$fieldO );
//set the filename
$filename = "prijave";
//call the function and pass the above array and filename as arguments
array_to_csv( $array, $filename );
//function to write array to csv file using fputcsv()
function array_to_csv( $array, $filename ) {
//open the csv file
//set the path for the file - use a+ to set file pointer to end of file
$out = fopen( "/path/to/output/directory/".$filename.".csv" , 'a+' );
//header - optional, remove if not needed
$header = array( "Column 1 Name","Column 2 Name","Column 3 Name","Column 4 Name","Column 5 Name","Column 6 Name",
"Column 7 Name","Column 8 Name","Column 9 Name","Column 10 Name","Column 11 Name","Column 12 Name",
"Column 13 Name","Column 14 Name","Column 15 Name"
);
//write the header - optional, remove if not needed
fputcsv ( $out, $header, "," );
//foreach loop is if you have a multidimensional array- uncomment if it is
//foreach( $array as $line ) {
//write each line of the array to csv file
fputcsv( $out, $array, "," );
//}
//close the file
fclose( $out );
}
?>
I have tested the above code and it works as it should. I have a header that is written to the file, along with the values from the array beneath each column.
Related
i have two columns in csv file Name and Phone . If i given phone number as a variable $searchStr = "6059574150"; it has to find number in csv file and i need that contact name to get access dynamicaly like this $data['Name'] instead of $data['0']
MY php code
$header = array();
$final_result = array();
$file = fopen('example.csv', 'r');
if($file){
$row = 1;
while ($data = fgetcsv($file, 10000, ",")){
if($row == 1){
$header = array_values($data);
}
else{
$final_result[] = array_combine($header, array_values($data));
}
$row++;
}
}
echo "<pre>";
print_r($final_result);
my output is like this
Array
(
[0] => Array
(
[Names] => MICHAEL
[Phone] => 6059342614
)
[1] => Array
(
[Names] => GLENN
[Phone] => 6056296061
)
)
how to directly access column ? like this $data['Name']
If phone numbers are unique, you could do something like this:
<?php
$final_result = array();
$file = fopen('example.csv', 'r');
if($file) {
$header = fgetcsv($file, 10000, ",");
while ($data = fgetcsv($file, 10000, ",")) {
$final_result[$data[1]] = $data[0];
}
}
?>
If you have more than one name (person) for each phone number, you can concatenate them $final_result[$data[1]] .= ',' . $data[0];.
Example result:
array (
phone1 => 'name1',
phone2 => 'name2',
phone3 => 'name3',
)
To search a name from a phone number you have to do: $final_result[phone_number] and you get the name.
In your output array "$final_result" you can look for a Name by phone number this way:
$foundKey = array_search('pone_number_to_search', array_column($final_result, "Phone"));
$foundNames = $final_result[$foundKey]["Names"];
I want to write a script for an api from a website. This website gives you the data in a text that is like a json text.
[ { "nickname":"dieeeeeeter", "votes":"9" }, { "nickname":"Honk", "votes":"9" },
I just want to add the nickname and the number of votes into my database, so I delete (replace) everything else.
$data = file_get_contents($filename);
$data = str_replace('"', '', $data);
$data = str_replace(':', '', $data);
$data = str_replace('{}', '', $data);
$data = str_replace('nickname', '', $data);
$data = str_replace('votes', '', $data);
So now my text output looks like this
{ Honk, 9 }, { dieeeeeeter, 9 }
But I don't know how I can but my data into a variable like "$username".
Can you help me ?
I suggest to use json_decode php function to convert json string to array and loop the array to get the values and insert them to database.
$json_string = '[ { "nickname":"dieeeeeeter", "votes":"9"}, { "nickname":"Honk", "votes":"9"}]';
$data_array = json_decode($json_string ,true);
print_r($data_array );
foreach($data_array as $data){
$nickname = trim($data['nickname']);
$votes = trim($data['votes']);
// insert query goes here
}
Out put of array will be like this
Array
(
[0] => Array
(
[nickname] => dieeeeeeter
[votes] => 9
)
[1] => Array
(
[nickname] => Honk
[votes] => 9
)
)
I have this sort of structure on a txt file.
[FILE_INFO]
[FIRST]
LOAD1= CPU
LOAD2 = RAM
[END_FIRST]
[GLOBAL_INDEX]
ELEC1=1235.12
GAZ2,1=1563.123
GAZ2,2= 28.56
[END_GLOBAL_INDEX]
[END_FILE_INFO]
What i need is to convert this txt structure to a php array , is this possible or txt structure is know ?
Array
(
[FILE_INFO] => Array
(
[FIRST] => Array
(
[LOAD1] => CPU
[LOAD2] => RAM
)
[GLOBAL_INDEX] => Array
(
[ELEC1] => 1235.12
[GAZ2] => Array
(
[1] => 1563.123
[2] => 28.56
)
)
)
)
Here is my approach:
$txt_file = file_get_contents("test.rt");
$rows = explode("\n", $txt_file);
$new_array = array(); $dimension = array();
foreach($rows as $row =>$data)
{
if($data[0] == "[" && substr($data, 0, 4) != "[END"){ // start
$output = str_replace( array('[',']') , '' , $data );
array_push($dimension, trim($output));
continue;
}else if(substr($data, 0, 4) == "[END"){ // end
$output = str_replace( array('[',']') , '' , $data );
array_pop($dimension);
continue;
}
$dim="";
foreach($dimension as $k=>$v){
$dim.= "['$v']";
}
$new_array.$dim[] = $data; // this is not working !!!!!
}
The problem is to position my cursor in the dimension of the array and insert the data
Try this:
<?php
$myfile = fopen("test.txt", "r");
// Iterate one line until end-of-file
while(!feof($myfile)) {
$text[] = fgets($myfile); // Add the data in an array
}
fclose($myfile);
print_r($text); // print the array
?>
This is the code I have and I am trying to get and encode the image contents as base64 but I keep ending up with the URL as a base64 string.
In the end I get images as an array from a API I need to transcode them to Base64 to store in a local DB.
This is based on the Gravity Forms API, Wordpress, PHP, mySQL, (LAMP) etc.
<?php
$images = array();
$body = array();
$imagesDecoded = array();
$imgUrls = array(
'1' => 'bg.jpg',
'2' => 'meeting.jpg',
'3' => 'testimonial.jpg',
'4' => 'works.jpg',
);
$imgUrls = array_map(function($el) {
return 'http://orlandojoes.co.uk/rimos/images/' . $el;
}, $imgUrls);
print'<pre>';
print_r($imgUrls);
print'</pre>';
foreach ($imgUrls as $image) {
$data = file_get_contents($imgUrls);
$data = base64_encode($imgUrls);
array_push($body, $data);
}
print '<pre>';
print_r ($body);
print '<pre>';
foreach ($body as $bodyimage) {
$dataDec = base64_decode($bodyimage);
array_push($imagesDecoded, $dataDec);
}
print '<pre>';
print_r ($imagesDecoded);
print '<pre>';
This is the output from when I run this code now:
Array
(
[ptSignature] => http://orlandojoes.co.uk/rimos/images/bg.jpg
[pSignature] => http://orlandojoes.co.uk/rimos/images/meeting.jpg
[witness1Signature] => http://orlandojoes.co.uk/rimos/images/testimonial.jpg
[witness2Signature] => http://orlandojoes.co.uk/rimos/images/works.jpg
)
Array
(
[0] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy9iZy5qcGc=
[1] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy9tZWV0aW5nLmpwZw==
[2] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy90ZXN0aW1vbmlhbC5qcGc=
[3] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy93b3Jrcy5qcGc=
)
Array
(
[0] => http://orlandojoes.co.uk/rimos/images/bg.jpg
[1] => http://orlandojoes.co.uk/rimos/images/meeting.jpg
[2] => http://orlandojoes.co.uk/rimos/images/testimonial.jpg
[3] => http://orlandojoes.co.uk/rimos/images/works.jpg
)
You have two bugs in your code.
$data = file_get_contents($imgUrls); // This is an array of URLs
$data = base64_encode($imgUrls); // You encode the URLs here!
Should be:
$data = file_get_contents($image); // $image instead of $imgUrls
$data = base64_encode($data); // $data instead of $imgUrls
Or simply:
$data = base64_encode(file_get_contents($image));
Side note, you don't need array_push() in your code, it's typically only needed if you want to push more than one item at one time. So, you can change it to just:
$body[] = $data;
i need to upload a .txt file in database.
my .txt file is exactly looks like
Name|Code|Email|Designation|Number|Salary|Age\t
syed|101|syed#gmail.com|trainee|7222877798|6000|21\t
hari|102|hari#gmail.com|trainee|9554512582|6000|23\t
i have need to separate it with | and then \t.
while getting array, the first one achieved as what i expect. but i cant able make \t explode.. can any one help me on this forum??
my routine is described below
if ($_POST['frmSubmit']) {
$file = $_FILES['frmUpload']['tmp_name']; // Get Temporary filename
$handle = fopen($file,"r"); // Open the file and read
while($strBookData = fgets($handle, 4096)) { // To get Array from .txt
$strDatas[] = $strBookData;
$strTableColumn = count($strBookData);
}
$strDatas = explode("|",implode($strDatas));
printArray($strDatas); exit;
if ($strDatas) {
$strInsertRecords = 0;
$strDuplicationRecords = 0;
if ($strTableColumn == 7) {
for($k=1; $k<count($strDatas); $k++) { //$k=1 is initialized because $k[0] is a header field array.
$strStatus = doCheckDuplication($strDatas[$k]['2']);
if ($strStatus == 0) {
// Insert Code
$strData = $strDatas[$k];
doInsertEmployeeDetails($strData['0'], $strData['1'], $strDatas[$k]['2'], $strData['3'], $strData['4'], $strData['5'], $strData['6']);
$strInsertRecords++; // To Get Inserted Records Count.
} else {
$strDuplicationRecords++; // To Get Duplication Records Count.
}
}
}
}
Hi this will split the text you provided.
$text = 'Name|Code|Email|Designation|Number|Salary|Age\t
syed|101|syed#gmail.com|trainee|7222877798|6000|21\t
hari|102|hari#gmail.com|trainee|9554512582|6000|23\t';
//remove line endings
$text = str_replace(array("\r\n", "\r", "\n"), "", $text);
$rows = explode('\t', $text);
$data = array();
foreach ($rows as $row){
//don't include empty lines
if(!empty( $row )){
$data[] = explode('|', $row);
}
}
echo '<pre>';
var_export( $data );
Outputs:
array (
0 =>
array (
0 => 'Name',
1 => 'Code',
2 => 'Email',
3 => 'Designation',
4 => 'Number',
5 => 'Salary',
6 => 'Age',
),
1 =>
array (
0 => 'syed',
1 => '101',
2 => 'syed#gmail.com',
3 => 'trainee',
4 => '7222877798',
5 => '6000',
6 => '21',
),
2 =>
array (
0 => 'hari',
1 => '102',
2 => 'hari#gmail.com',
3 => 'trainee',
4 => '9554512582',
5 => '6000',
6 => '23',
),
);
However that said, there is a lot going on in your example, as for reading the file in. If it's not to large the best bet would be to use file_get_contents() that will read the whole file in one go. Otherwise in this part
$handle = fopen($file,"r"); // Open the file and read
while($strBookData = fgets($handle, 4096)) { // To get Array from
$strDatas[] = $strBookData;
$strTableColumn = count($strBookData);
}
You would be better off just concatenating the text.
$strDatas = '';
$handle = fopen($file,"r"); // Open the file and read
while($strBookData = fgets($handle, 4096)) { // To get Array from
$strDatas .= $strBookData;
}
And then splitting like I did above.
I think that you should first explode using '\t' as delimiter to get the substrings separated by \t (Name|Code|Email|Designation|Number|Salary|Age)
and then explode each substring using '|' as delimiter.
I wish that can help you