I have an array of results and I want to create csv file for it. but if the result is valid I want to add the email in the valid csv file and if it is invalid then in the invalid csv file. but I am unable to do this. it adds all the emails to clean csv file and the invalid csv is empty. any suggestions
the results are looks like this:
Array
(
[0] => Array
(
[email] => tamas.szabo#millionverifier.com
[result] => valid
)
[1] => Array
(
[email] => support#millionverifier.com
[result] => valid
)
)
Here is my condition
// creating dirty and clean file
$clean_emails = fopen(UPLOAD_DIRECTORY . '/clean/' . $file_name_new . '.' . $extension, 'w');
$dirty_emails = fopen(UPLOAD_DIRECTORY . '/dirty/' . $file_name_new . '.' . $extension, 'w');
// adding headers to them
fputcsv($clean_emails, $headers);
fputcsv($dirty_emails, $headers);
if ($results[$i]['result'] === 'valid') {
// adding clean emails to csv
foreach ($results as $row) {
fputcsv($clean_emails, $row);
}
fclose($clean_emails);
} elseif ($results[$i]['result'] === 'invalid') {
// adding dirty emails to csv
foreach ($results as $row) {
fputcsv($dirty_emails, $row);
}
fclose($dirty_emails);
} else {
// if there are not any dirty or clean emails add them unknown to csv
$unknown_emails = fopen(UPLOAD_DIRECTORY . '/unknown/' . $file_name_new . '.' . $extension, 'w');
fputcsv($unknown_emails, $row);
fclose($unknown_emails);
}
May be you want line-by-line separation?
// creating dirty and clean file
$clean_emails = fopen(UPLOAD_DIRECTORY . '/clean/' . $file_name_new . '.' . $extension, 'w');
$dirty_emails = fopen(UPLOAD_DIRECTORY . '/dirty/' . $file_name_new . '.' . $extension, 'w');
$unknown_emails = null; // No file yet
// adding headers to them
fputcsv($clean_emails, $headers);
fputcsv($dirty_emails, $headers);
foreach ($results as $row) { // Scan each row
if ($row['result'] === 'valid') {
fputcsv($clean_emails, $row);
} elseif ($row['result'] === 'invalid') {
fputcsv($dirty_emails, $row);
} else { // found something else
if (!isset($unknown_emails)) { // Open file if it was not
$unknown_emails = fopen(UPLOAD_DIRECTORY . '/unknown/' . $file_name_new . '.' . $extension, 'w');
fputcsv($unknown_emails, $headers); // Add headers ?
}
fputcsv($unknown_emails, $row);
}
} // end loop
fclose($clean_emails);
fclose($dirty_emails);
if (isset($unknown_emails)) {
fclose($unknown_emails); // Close 'unknown' if it was opened
}
Related
I have a image named Dark-Green.jpg but the output of function is DARK-GREEN.jpg so the image is not displaying due to case-sensitive.
So how can I fetch the image?
UPDATE
Below is my output of the array.
$output = Array
(
[WE05-5040*L] => Array
(
[qty] => 1
[stitching_category] => 2
[sku_image] => skuimages/WE05/DARK-GREEN.jpg
)
)
Then I am using this array in foreach loop like below.
foreach ($output as $ok => $op) {
$itemQty = $op['qty'];
$itemImagePath = $op['sku_image'];
echo "{$ok} has qty: {$itemQty} and the image as below.";
echo "<img src='{$itemImagePath}' width='50%' />"
}
Try this:
function getFile ($filename){
$files = glob($dir . '/*');
$filename = strtolower($filename);
foreach($files as $file) {
if (strtolower($file) == $filename){
return $file;
}
}
return false;
}
I am using parse_ini_file to parse an ini file using PHP.
Now I first upload an INI file to my server then open it and allow user to mak custom changes to the file.
Now once users has edited the file i get the data from post and save the file back to server. But Now i dont get my sections. INIdetails,Dialplan in the updated file so when i also want to write that to file how to do that?
This is the code :
$this->data['parameters'] = parse_ini_file($path.$filename,true);
/*Getting Our POST DATA from View*/
$data = array(
'SipUserName' => $this->input->post('SipUserName') ,
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'Param_1' => $this->input->post('Param_1'),
'Param_2' => $this->input->post('Param_2')
);
/*Creating New file with the name of customer loggedin*/
$name = $this->session->userdata('username');
$ext = $this->session->userdata('extension');
$custom_file = fopen('uploads/'.$name.'_'.$ext.'.ini', 'w');
fwrite($custom_file, "[INIDetails]\n");
foreach ($data as $key => $value)
{
fwrite($custom_file, " $key = $value\n");
}
fclose($custom_file);
/*Setting path to New CUSTOM file with customer name as prefix*/
$file = $path.$custom_file;
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
/*Creates ini file, dumps array to string and creates .INI file*/
write_php_ini($data,$file);
The culprit from your previous code is that your array is not formatted correctly, it should be array of arrays to achieve what you want.
Try below code:
// First read the ini file that the user was editing
// Your idea to read the existing ini file is good, since it will generate you the structured array
$previous_data = parse_ini_file($path . $filename, true);
// Overwrite/edit the previous_data using user's post data
$previous_data['INIDetails']['SipUserName'] = $this->input->post('SipUserName');
$previous_data['INIDetails']['Password'] = $this->input->post('Password');
$previous_data['INIDetails']['Domain'] = $this->input->post('Domain');
$previous_data['INIDetails']['Proxy'] = $this->input->post('Proxy');
$previous_data['INIDetails']['Port'] = $this->input->post('Port');
$previous_data['INIDetails']['SipAuthName'] = $this->input->post('SipAuthName');
$previous_data['INIDetails']['DisplayName'] = $this->input->post('DisplayName');
$previous_data['INIDetails']['ServerMode'] = $this->input->post('ServerMode');
$previous_data['INIDetails']['UCServer'] = $this->input->post('UCServer');
$previous_data['INIDetails']['UCUserName'] = $this->input->post('UCUserName');
$previous_data['INIDetails']['UCPassword'] = $this->input->post('UCPassword');
$previous_data['DialPlan']['DP_Exception'] = $this->input->post('DP_Exception');
$previous_data['DialPlan']['DP_Rule1'] = $this->input->post('DP_Rule1');
$previous_data['DialPlan']['DP_Rule2'] = $this->input->post('DP_Rule2');
$previous_data['DialPlan']['OperationMode'] = $this->input->post('OperationMode');
$previous_data['DialPlan']['MutePkey'] = $this->input->post('MutePkey');
$previous_data['DialPlan']['Codec'] = $this->input->post('Codec');
$previous_data['DialPlan']['PTime'] = $this->input->post('PTime');
$previous_data['DialPlan']['AudioMode'] = $this->input->post('AudioMode');
$previous_data['DialPlan']['SoftwareAEC'] = $this->input->post('SoftwareAEC');
$previous_data['DialPlan']['EchoTailLength'] = $this->input->post('EchoTailLength');
$previous_data['DialPlan']['PlaybackBuffer'] = $this->input->post('PlaybackBuffer');
$previous_data['DialPlan']['CaptureBuffer'] = $this->input->post('CaptureBuffer');
$previous_data['DialPlan']['JBPrefetchDelay'] = $this->input->post('JBPrefetchDelay');
$previous_data['DialPlan']['JBMaxDelay'] = $this->input->post('JBMaxDelay');
$previous_data['DialPlan']['SipToS'] = $this->input->post('SipToS');
$previous_data['DialPlan']['RTPToS'] = $this->input->post('RTPToS');
$previous_data['DialPlan']['LogLevel'] = $this->input->post('LogLevel');
// Set Name of New file with the name of customer logged in
$name = $this->session->userdata('username');
$ext = $this->session->userdata('extension');
$custom_file = "$name_$ext.ini";
$new_filename = $path . $custom_file;
// Write the INI file
write_php_ini($data, $new_filename);
function write_php_ini($array, $new_filename)
{
$res = array();
foreach ($array as $key => $val) {
if (is_array($val)) {
$res[] = "[$key]";
foreach ($val as $skey => $sval) {
$res[] = "$skey = " . (is_numeric($sval) ? $sval : '"' . $sval . '"');
}
} else {
$res[] = "$key = " . (is_numeric($val) ? $val : '"' . $val . '"');
}
}
safefilerewrite($new_filename, implode("\r\n", $res));
}
function safefilerewrite($new_filename, $dataToSave)
{
if ($fp = fopen($new_filename, 'w')) {
$startTime = microtime(true);
do {
$canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if (!$canWrite) {
usleep(round(rand(0, 100) * 1000));
}
} while ((!$canWrite) and ((microtime(true) - $startTime) < 5));
//file was locked so now we can store information
if ($canWrite) {
fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
From your previous code, there are bunch of inappropriate codes which I remove. Also, too many inconsistencies like Method naming, variable naming etc.
If your function was named Camel cased then through out your code it must be named as camel-cased. If your variables are with underscore, then through out your code, they must have underscore for two or more worded variable.
I didn't edit the naming convention of your code so you won't be confused but i suggest to have a consistent naming convention through out your project.
UPDATED:
based on your answer, it seems like you changed your whole code. I would like to provide another way using nested foreach and passing by reference that save couple of lines:
$this->data['params'] = $this->parameter_m->get();
$this->data['parameters'] = parse_ini_file($path . $filename, true);
foreach ($this->data['parameters'] as $key_header => &$value_header) {
foreach ($value_header as $key_item => &$value_item) {
$value_item = $this->input->post($key_item);
}
}
$this->load->helper('file');
$this->load->library('ini');
$file = $path . $filename;
$ini = new INI($file);
$ini->read($file);
$ini->write($file, $this->data['parameters']);
Finally i got an answer:
I will loop through what i get from POST and will get each array's key. And then i will give the resultant to my Write Method
$this->data['params'] = $this->parameter_m->get();
/*Getting the parameters to display on view*/
$this->data['parameters'] = parse_ini_file($path.$filename,true);
while (current($this->data['parameters']) )
{
$param_set = current($this->data['parameters']);
$param_type = key($this->data['parameters']);
foreach ($param_set as $key =>$value)
{
$this->data['parameters'][$param_type][$key] = $this->input->post($key);
}
next($this->data['parameters']);
}
$this->load->helper('file');
$this->load->library('ini');
$file = $path.$filename;
$ini = new INI($file);
$ini->read($file);
$ini->write($file, $this->data['parameters']);
I have a document called subjects.txt in the following format:
DateCreated,Subject,Link
18.10.2015,"Math",http: //address.html
17.10.2015,"English",http: //address.html
18.10.2015,"English",http: //address.html
19.10.2015,"Science",http: //address.html
17.10.2015,"Math",http: //address.html
The file contains URLs of sites created based on a school subject. There can be more than one site for a subject.
The goal is to use PHP to open, read, and display the contents of the file in the following format:
Math
Link 1
Link 2
English
Link 1
Link 2
Science (because there's only one link, the name of the subject is the
link)
So far I've been able to open and read the file:
$file = "./subjects.txt";
$subjects = file_get_contents($file);
I'm having trouble trying to determine how to go about writing the file in specified format.
I've tried using explode to separate the elements with "," - however I don't know where to go from there.
Your input file looks to be in Comma-separated values (CSV) format. PHP has a built-in fgetcsv function designed to make reading CSV data from a file easy.
<?php
$file = './subjects.txt';
$fh = fopen($file, 'r');
if ($fh === false) {
die("Can not read {$file}");
}
$data = array();
while (($row = fgetcsv($fh, 1000, ',')) !== false) {
if ($row[0] === 'DateCreated') {
// Ignore the column header row
continue;
}
list($date, $subject, $link) = $row;
if (!isset($data[$subject])) {
$data[$subject] = array();
}
$data[$subject][] = $link;
}
fclose($fh);
foreach ($data as $subject => $links) {
// TODO: output each subject here
}
Here is another version
<?php
$file = "./subjects.txt";
$h = fopen($file, "r");
if($h !== false) {
$subjects = [];
$data = [];
while(!feof($h)) {
if($line = trim(fgets($h))) {
$line = explode(",", $line);
if(!in_array("DateCreated",$line)) {
array_push($subjects, $line);
}
}
}
fclose($h);
foreach ($subjects as $subject) {
if(!isset($data[$subject[1]])) {
$data[$subject[1]] = [];
}
$data[$subject[1]][] = $subject[2];
}
foreach ($data as $subject => $links) {
if(count($links) == 1) {
echo "<p>$subject</p>\n";
} else {
$i = 1;
echo "<p>$subject</p>\n";
echo "<ul>\n";
foreach ($links as $link) {
echo "<li>link$i</li>\n";
$i++;
}
echo "</ul>\n";
}
}
}
?>
The problem using file_get_contents() is that retrieves all the file contents into $subjects.
You have to use a different approach. For example fgets():
$fp = fopen("./subjects.txt", "r");
if ($fp){
while (($line = fgets($fp)) !== false){
// So here you can treat each line individually.
// You can use explode (";", $line) for example if the line is not empty
}
}
fclose($fp);
Using fgets() will allow you to parse each of the file's lines individually.
As stated doing this with a database would be much easier probably 3 lines of code. Here's one approach you could use though.
$data = '18.10.2015,"Math",http: //address.html
17.10.2015,"English",http: //address1.html
18.10.2015,"English",http: //address2.html
19.10.2015,"Science",http: //address3.html
17.10.2015,"Math",http: //address4.html';
preg_match_all('~^(.*?),"(.*?)",(.*?)$~m', $data, $fields);
array_multisort($fields[2], SORT_STRING, $fields[1], $fields[3]);
$lastcat = '';
foreach($fields[2] as $key => $cat) {
if($cat != $lastcat) {
echo $cat . "\n";
}
$lastcat = $cat;
echo $fields[3][$key] . "\n";
}
Output:
English
http: //address1.html
http: //address2.html
Math
http: //address4.html
http: //address.html
Science
http: //address3.html
The array_multisort is how the categories are grouped.
Here's a regex101 demo of what that regex is doing. https://regex101.com/r/wN3nB2/1
Update for single record check (only ran 1 test on it):
$data = '18.10.2015,"Math",http: //address.html
17.10.2015,"English",http: //address1.html
18.10.2015,"English",http: //address2.html
19.10.2015,"Science",http: //address3.html
17.10.2015,"Math",http: //address4.html';
preg_match_all('~^(.*?),"(.*?)",(.*?)$~m', $data, $fields);
array_multisort($fields[2], SORT_STRING, $fields[1], $fields[3]);
$lastcat = '';
foreach($fields[2] as $key => $cat) {
if((empty($fields[2][($key +1)]) && $cat != $lastcat)|| ($cat != $lastcat && !empty($fields[2][($key +1)]) && $fields[2][($key +1)] != $cat)) {
//single record
echo $cat . $fields[3][$key] . "\n";
} else {
if($cat != $lastcat) {
echo $cat . "\n";
}
$lastcat = $cat;
echo $fields[3][$key] . "\n";
}
}
i make a template in which i select multiple files and i make php page in which i upload the files but when i upload the files it gives me error like
Warning: pathinfo() expects parameter 1 to be string, array given in C:\xampp\htdocs\jobboard\system\user-scripts\classifieds\apply_now.php on line 67
here is my code:
<input type="file" name="file_tmp[]" multiple />
and here is my apply_now.php:
if (!empty($_FILES['file_tmp']['name'])){
$fileFormats = explode(',',SJB_System::getSettingByName('file_valid_types'));
foreach ( $_FILES['file_tmp']['name'] as $file ) {
$fileInfo = pathinfo($file);
if ( !in_array(strtolower($fileInfo['extension']), $fileFormats) ) {
$errors['NOT_SUPPORTED_FILE_FORMAT'] = strtolower($fileInfo['extension']) . ' ' . SJB_I18N::getInstance()->gettext(null, 'is not in an acceptable file format');
}
}
}
The error is caused by the fact that you are giving an array as argument, instead of a string, just as the error message tells you.
This can be fixed by changing your foreach code to the following:
foreach ( $_FILES['file_tmp']['name'] as $key => $file ) {
$fileInfo = pathinfo($_FILES['file_tmp']['name'][$key]);
if ( !in_array(strtolower($fileInfo['extension']), $fileFormats) ) {
$errors['NOT_SUPPORTED_FILE_FORMAT'] = strtolower($fileInfo['extension']) . ' ' . SJB_I18N::getInstance()->gettext(null, 'is not in an acceptable file format');
}
}
Please also refer to my code in my answer on your previous question: https://stackoverflow.com/a/22355746/2539335
If you upload many files then $_FILES['file_tmp']['name'] will be an array.
You should make foreach loop
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
In you code replace:
$fileInfo = pathinfo($_FILES['file_tmp']['name']);
if ( !in_array(strtolower($fileInfo['extension']), $fileFormats) ) {
$errors['NOT_SUPPORTED_FILE_FORMAT'] = strtolower($fileInfo['extension']) . ' ' . SJB_I18N::getInstance()->gettext(null, 'is not in an acceptable file format');
}
With:
foreach ( $_FILES['file_tmp']['name'] as $file ) {
$fileInfo = pathinfo($file);
if ( !in_array(strtolower($fileInfo['extension']), $fileFormats) ) {
$errors['NOT_SUPPORTED_FILE_FORMAT'] = strtolower($fileInfo['extension']) . ' ' . SJB_I18N::getInstance()->gettext(null, 'is not in an acceptable file format');
}
}
Hello I'm trying to get all the values from $_POST request and to log it.
This my code:
<?php
$file = 'error_log.log';
$info = date("Y-m-d H:i:s")." - ".print_r($_POST, true)."\n";
foreach ($_POST as $key => $value) {
foreach($value as $k => $v) {
$info .= $k."\n";
$info .= $v."\n";
}
}
$current = file_get_contents($file);
$current .= $info;
file_put_contents($file, $current);
?>
But my problem is that all I get is "Array".
Like this:
2014-01-01 17:32:50 - Array
(
)
2014-01-01 17:34:13 - Array
(
)
2014-01-01 17:47:39 - Array
(
)
2014-01-01 17:47:40 - Array
(
)
The array comes from print_r($_POST, true);. $_POST is always an array and if array is empty that is the correct output you except. So basicly this means you don't send anything to as POST maybe you are using get ?
What you could do is check if anything is posted at all.
if (count($_POST) > 0) {
$info .= print_r($_POST, true);
}
If you are redirecting user to this page in case of error, the POST values won't be redirected with the user. And if this is an error catching page, maybe you should get save $_SERVER['REQUEST_URI'] along the data, so you know in which page the error happend.
Also as I said in my comment you could optimize your file writing with this.
file_put_contents($file, $info, FILE_APPEND | LOCK_EX);
It locks the file, so other scripts can't write to it at a same time, and appends the info to the end of the file. So you could replace these lines with just one command.
$current = file_get_contents($file);
$current .= $info;
file_put_contents($file, $current);
The whole script
<?php
$file = 'error_log.log';
$info = date("Y-m-d H:i:s") . " - " . $_SERVER['REQUEST_URI'] . "\n";
$info .= "POST: " . ((count($_POST))?print_r($_POST,true):"EMPTY\n");
$info .= "GET : " . ((count($_GET))?print_r($_GET,true):"EMPTY\n") . "\n";
file_put_contents($file, $info, FILE_APPEND | LOCK_EX);
Output example
2014-01-01 17:33:25 - /stack/error.php
POST: EMPTY
GET : EMPTY
2014-01-01 17:34:11 - /stack/error.php?ads=bsd&error=true
POST: EMPTY
GET : Array
(
[ads] => bsd
[error] => true
)
You've made it more complex than it is. Instead of:
foreach ($_POST as $key => $value) {
foreach($value as $k => $v)
{
$info .= $k."\n";
$info .= $v."\n";
}
}
It's just
foreach ($_POST as $key => $value) {
$info .= $key."\n";
$info .= $value."\n";
}