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
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 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
?>
I have to search through an Excel file and get the numbers that have a comma as a decimal point and convert it to a decimal point.(ex: 23,56 -> 23.56, 23123,566 -> 23123.566). I have already exported the excel file to .csv and put all contents into arrays but I have trouble finding the numbers with comma.
This is how one of my array looks like:
Array
(
[A1] => 1
[A2] => 123123
[A3] => dasdadwa
[A4] => 6,7
[A5] => 24f,5
[A6] => f5,5
[A7] => dasdad,fsdfsdfsfsasada dasdasd
[A8] => aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
[A9] => dasdasd
[A10] => q231e
[A11] =>
[A12] => 0
[A13] =>
[A14] =>
[A15] => 1
[A16] => 123123
[A17] => dasdadwa
[A18] => 6,7
[A19] => 24f,5
[A20] => f5,5
[A21] => dasdad,fsdfsdfsfsasada dasdasd
[A22] =>
[A23] =>
[A24] => q231e
[A25] =>
[A26] => 0
[A27] =>
[A28] =>
[A29] => 1
[A30] => 123123
[A31] => dasdadwa
[A32] => 6,7
[A33] => 24f,5
[A34] => f5,5
[A35] => dasdad,fsdfsdfsfsasada dasdasd
[A36] =>
[A37] =>
[A38] => q231e
[A39] =>
[A40] =>
[A41] =>
[A42] =>
)
I'm only interested in the characters that have only numbers and a comma but it is troublesome because those entries are strings. I have tried messing with regex but I just could not get it to work.
Here is what i have so far:
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$contents = csv_to_array($filename.'.csv');
foreach($contents as $val)
{
//If $val is a number separated by comma
//Replace comma with . (str_replace(',','.');, $val);)
}
Just simple pattern which will replace only your pattern:
//rest od your code and now:
foreach($contents as $key => $val)
{
$contents[$key] = preg_replace('/^(\d+),(\d+)$/', '\1.\2', $val);
}
This code will touch only strings like 2,3. Strings like this ff,333 will not be touch
Since you would like to extract only decimals, I suggest using regex, like this:
foreach($contents as $val) {
// if $val is a number separated by comma
if (preg_match('/^[0-9]+,[0-9]+$/', $val) == 1) {
// transform into float with two decimals and dot as decimal separator
$float = number_format($val, 2, '.');
}
}
Edit: updated regex pattern following comments.
Like this?
foreach($contents as $val)
{
if (strpos($val, ',') !== false) {
$val = str_replace(',', '.', $val);
}
}
my_custom_table:
id int(11)
product_type varchar(210)
product_serial varchar(210)
created_at datetime
//Upload CSV File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['upload_csv']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['upload_csv']['name'] ." uploaded successfully." . "</h1>";
}
//Import uploaded file to Database
$handle = fopen($_FILES['upload_csv']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$wpdb->insert("my_custom_table", array(
"product_type" => $data[0],
"product_serial" => $data[1],
"created_at" => current_time('mysql', 1)
));
}
fclose($handle);
print "Import done";
}
Print $data output with delimiter ,:
Array
(
[0] => Product Name;product_serial
)
Array
(
[0] => iPhone 6;iphone-002
)
Array
(
[0] => iPhone 6;iphone-003
)
Print $data output with delimiter ;:
Array
(
[0] => Product Name
[1] => product_serial
)
Array
(
[0] => iPhone 6
[1] => iphone-002
)
Array
(
[0] => iPhone 6
[1] => iphone-003
)
Using above, Product Name and product_serial also gets inserted in DB which should be prevented. Also delimiter , does not output correct array while ; does.
How can I prevent CSV column names insertion and insert correct value in Database?
P.S: Using OpenOffice for CSV data insertion. Could formatting be an issue with delimiter ?
The general rule of thumb is the first line of CSV is the column names, therefore a quick skip counter will remove the first row for you:
$counter = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// Skip the first row as is likely column names
if ($counter === 0) {
$counter++;
continue;
}
// Insert the row into the database
$wpdb->insert("my_custom_table", array(
"product_type" => $data[0],
"product_serial" => $data[1],
"created_at" => current_time('mysql', 1)
));
}
The other problem is CSV files can have varying column and row delimiters (AKA sometimes columns are sperated by comma, and other times semi colons ...etc) making parsing CSV quite difficult. I this example it seems your column delimiter is semi-colon so modifying your function parameters may fix it for you:
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
If you really must support multiple types of delimiter, the following code snippet may help you:
$csvFilePath = $_FILES['upload_csv']['tmp_name'];
$delimiter = $this->detectDelimiter($csvFilePath);
public function detectDelimiter($csvFile)
{
$delimiters = array(
';' => 0,
',' => 0,
"\t" => 0,
"|" => 0
);
$handle = fopen($csvFile, "r");
$firstLine = fgets($handle);
fclose($handle);
foreach ($delimiters as $delimiter => &$count) {
$count = count(str_getcsv($firstLine, $delimiter));
}
return array_search(max($delimiters), $delimiters);
}
Detect snippet taken from: HERE
Hope this helps.
I have this OUTPUT array from Decode function down:
Array ( [
] =>
[HostName] => Survival4fun
[GameType] => SMP
[Version] => 1.5.2
[Plugins] => Array
(
[0] => WorldEdit
)
[Map] => world
[Players] => 0
[MaxPlayers] => 10
[HostPort] => 25608
[HostIp] => 31.133.13.99
[RawPlugins] => WorldEdit5.5.6;
[Software] => CraftBukkitonBukkit1.5.2-R0.1
[Status] => online
[Ping] => 15ms
[
] =>
[PlayersOnline] => Array
(
[P0] => NoPlayers
)
[
] => )
And so, you can see this:
[
] =>
How can I remove it ? I tried using str_replace("\n", "", $arr); But this doesn't work.
Here is the original array - http://status.mc-host.cz/s8.mc-host.cz:25608-feed
And here is my function code:
Function Decode_query($link) {
$data = file($link, FILE_IGNORE_NEW_LINES);
$arr = array();
$string = array("[", "]", " ", "(", ")", "Array", "\n", "\r");
$replace = array("", "", "", "", "", "", "", "");
ForEach ($data as $line) {
$s = str_replace($string, $replace, $line);
If (Empty($s)) {} Else {
$stat = explode("=>", $s);
$P = str_replace("P", "", $stat[0]);
If (is_numeric($stat[0])) {
$arr["Plugins"][$stat[0]] = $stat[1];
}
ElseIf (is_numeric($P)) {
$arr['PlayersOnline'][$stat[0]] = $stat[1];
} Else {
$arr[$stat[0]] = $stat[1];
}
}
}
Return $arr;
}
$arr = Decode_query("http://status.mc-host.cz/s8.mc-host.cz:25608-feed");
Print_r($arr);
Thanks for help and sorry for long question..
You could use a regex to scan for keys that are composed of only whitespace:
$keys = array_keys($your_array);
$blank_keys = preg_grep('/^\s*$/', $keys);
foreach($blank_keys as $blank) {
unset($your_array[$blank]);
}
I would work with trim in stead of str_replace. It is less expensive, and it takes care of the trailing spaces and whatever whitespace there may be. In your case your function would probably look something like this:
Function Decode_query($link) {
// fetch the data
$data = file($link, FILE_IGNORE_NEW_LINES);
// prepare output array
$arr = array('Plugins' => array(), 'PlayersOnline' => array());
// prepare the list of characters we want to remove
$removeChars = ' \t\n\r[]';
ForEach ($data as $line) {
// split line into key, value
$stat = explode("=>", $line);
// no 2 elements, means no '=>', so ignore line
if (count($stat) < 2) continue;
// remove unwanted characters from key
$trimmed = trim($stat[0], $removeChars);
$pTrimmed = trim($trimmed, 'P');
// if key = plugins, ignore line
if ($trimmed == 'Plugins') continue;
// if key is numeric
If (is_numeric($trimmed)) {
// store in plugins subarray
$arr['Plugins'][$trimmed] = trim($stat[1]);
}
// if (key - P) is numeric
ElseIf (is_numeric($pTrimmed)) {
// store in players online subarray
$arr['PlayersOnline'][$pTrimmed] = trim($stat[1]);
} Else {
// all others store in level 1 array
$arr[$trimmed] = trim($stat[1]);
}
}
Return $arr;
}
I didn't test the code, but I think it should work fine.
PS: You can never put enough comments in your code, may seem a waste of time at first, but you, or anyone who has to work on your code, will be very grateful some day...