getting file name without file extention in my php code - php

what i'm trying to do here, in my php code below i have to set file name manually and i want to make it some how it grabds the file name automatically but without file extention
here's part of my code where i want to get file name
$Pages = array(
'clothes' => 'Clothes',
'shirt' => 'shirt',
'this-shirt' => 'This Shirt'
);
where it says "this-shirt" is file name and i want it to be set automatically instead of i write it down everytime i create a page. also here's full code
<?php
$Pages = array(
'clothes' => 'Clothes',
'shirt' => 'shirt',
'this-shirt' => 'This Shirt'
);
$path = $_SERVER["PHP_SELF"];
$parts = explode('/', $path);
if (count($parts) < 2) {
echo("home");
} else {
echo ("Home » ");
for ($i = 2; $i < count($parts); $i++) {
if (!strstr($parts[$i], ".")) {
echo("<a href=\"");
for ($j = 0; $j <= $i; $j++) {
echo $parts[$j] . "/";
};
echo("\">" . str_replace('-', ' ', $Pages[$parts[$i]]) . "</a> » ");
} else {
$str = $parts[$i];
$pos = strrpos($str, ".");
$parts[$i] = substr($str, 0, $pos);
echo str_replace('-', ' ', $Pages[$parts[$i]]);
}
}
}
hope you get the idea. thanks

This should do it:
// get this-shirt.php from the URL
$file = basename($_SERVER["PHP_SELF"]);
// pure magic
$filename = (count(explode('.', $file)) === 1 ? $file : implode('.', array_slice(explode('.', $file), 0, (count(explode('.', $file))-1))));
$Pages = array(
'clothes' => 'Clothes',
'shirt' => 'shirt',
$filename => 'This Shirt' // use $filename to declare the array's key
);

Related

Laravel Auto-Link library

I'm looking for a travel auto-link detection.
I'm trying to make a social media website and when my users post URLs I need it so like shows instead of just normal text.
Try Autologin for Laravel by dwightwatson, which provides you to generate URLs that will provide automatic login to your application and then redirect to the appropriate location
As far as I know, there's no equivalent in the Laravel's core for the auto_link() funtion helper from Code Igniter (assuming you are refering to the CI version).
Anyway, it's very simple to grab that code and use it in Laravel for a quick an dirty workaround. I just did casually looking for the same issue.
Put in your App directory a container class for your helpers (or any containter for the matter, it's just need to be discovered by the framework), in this case I put a UrlHelpers.php file. Then, inside of it put this two static functions grabbed for the CI version:
class UrlHelpers
{
static function auto_link($str, $type = 'both', $popup = FALSE)
{
// Find and replace any URLs.
if ($type !== 'email' && preg_match_all('#(\w*://|www\.)[^\s()<>;]+\w#i', $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
// Set our target HTML if using popup links.
$target = ($popup) ? ' target="_blank"' : '';
// We process the links in reverse order (last -> first) so that
// the returned string offsets from preg_match_all() are not
// moved as we add more HTML.
foreach (array_reverse($matches) as $match) {
// $match[0] is the matched string/link
// $match[1] is either a protocol prefix or 'www.'
//
// With PREG_OFFSET_CAPTURE, both of the above is an array,
// where the actual value is held in [0] and its offset at the [1] index.
$a = '<a href="' . (strpos($match[1][0], '/') ? '' : 'http://') . $match[0][0] . '"' . $target . '>' . $match[0][0] . '</a>';
$str = substr_replace($str, $a, $match[0][1], strlen($match[0][0]));
}
}
// Find and replace any emails.
if ($type !== 'url' && preg_match_all('#([\w\.\-\+]+#[a-z0-9\-]+\.[a-z0-9\-\.]+[^[:punct:]\s])#i', $str, $matches, PREG_OFFSET_CAPTURE)) {
foreach (array_reverse($matches[0]) as $match) {
if (filter_var($match[0], FILTER_VALIDATE_EMAIL) !== FALSE) {
$str = substr_replace($str, static::safe_mailto($match[0]), $match[1], strlen($match[0]));
}
}
}
return $str;
}
static function safe_mailto($email, $title = '', $attributes = '')
{
$title = (string)$title;
if ($title === '') {
$title = $email;
}
$x = str_split('<a href="mailto:', 1);
for ($i = 0, $l = strlen($email); $i < $l; $i++) {
$x[] = '|' . ord($email[$i]);
}
$x[] = '"';
if ($attributes !== '') {
if (is_array($attributes)) {
foreach ($attributes as $key => $val) {
$x[] = ' ' . $key . '="';
for ($i = 0, $l = strlen($val); $i < $l; $i++) {
$x[] = '|' . ord($val[$i]);
}
$x[] = '"';
}
} else {
for ($i = 0, $l = strlen($attributes); $i < $l; $i++) {
$x[] = $attributes[$i];
}
}
}
$x[] = '>';
$temp = array();
for ($i = 0, $l = strlen($title); $i < $l; $i++) {
$ordinal = ord($title[$i]);
if ($ordinal < 128) {
$x[] = '|' . $ordinal;
} else {
if (count($temp) === 0) {
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) === $count) {
$number = ($count === 3)
? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64)
: (($temp[0] % 32) * 64) + ($temp[1] % 64);
$x[] = '|' . $number;
$count = 1;
$temp = array();
}
}
}
$x[] = '<';
$x[] = '/';
$x[] = 'a';
$x[] = '>';
$x = array_reverse($x);
$output = "<script type=\"text/javascript\">\n"
. "\t//<![CDATA[\n"
. "\tvar l=new Array();\n";
for ($i = 0, $c = count($x); $i < $c; $i++) {
$output .= "\tl[" . $i . "] = '" . $x[$i] . "';\n";
}
$output .= "\n\tfor (var i = l.length-1; i >= 0; i=i-1) {\n"
. "\t\tif (l[i].substring(0, 1) === '|') document.write(\"&#\"+unescape(l[i].substring(1))+\";\");\n"
. "\t\telse document.write(unescape(l[i]));\n"
. "\t}\n"
. "\t//]]>\n"
. '</script>';
return $output;
}
}
The function safe_mailto is used in case there are email links in your string. If you don't need it you are free to modify the code.
Then you could use the helper class like this in any part of your Laravel code as usually (here inside a blade template, but the principle is the same):
<p>{!! \App\Helpers\Helpers::auto_link($string) !!}</p>
Quick and dirty, and It works. Hope to have helped. ¡Good luck!

getting directory of page using php

what i am trying to do is to get directory of my page like this
Home / Clothes / Something
i have tried this but i didn't understand a lot in this but it doesn't work as i want it
<?php
// current directory
echo getcwd() . "\n";
chdir('cvs');
// current directory
echo getcwd() . "\n";
?>
here's example what i need to do
my page is example.com/clothes/something.php
and on that page "something.php" i want to echo out something like this
Home / clothes / Something
i forget what this was called but hope you understand
<?php
$path = $_SERVER["PHP_SELF"];
$parts = explode('/',$path);
if (count($parts) < 2)
{
echo("home");
}
else
{
echo ("Home » ");
for ($i = 1; $i < count($parts); $i++)
{
if (!strstr($parts[$i],"."))
{
echo("<a href=\"");
for ($j = 0; $j <= $i; $j++) {echo $parts[$j]."/";};
echo("\">". str_replace('-', ' ', $parts[$i])."</a> » ");
}
else
{
$str = $parts[$i];
$pos = strrpos($str,".");
$parts[$i] = substr($str, 0, $pos);
echo str_replace('-', ' ', $parts[$i]);
};
};
};
?>
Try something like this:
$subPath = '';
$path = explode('/', $_SERVER['REQUEST_URI']);
array_shift($path);
foreach ($path as $segment) {
$subPath.= $segment.'/';
echo "$segment / ";
}
You may need to tweak it a bit, but that's the basic idea.
[EDIT]
Or maybe something like this:
$Pages = [
'/clothes' => 'Clothes',
'/clothes/something.php' => 'Something'
];
$subPath = '';
$BreadCrumbs = [];
$path = explode('/', $_SERVER['REQUEST_URI']);
array_shift($path);
foreach ($path as $segment) {
$subPath.= '/'.$segment;
$BreadCrumbs[] = "$Pages[$subPath]";
}
echo implode(' > ', $BreadCrumbs);
If your version of PHP is before 5.4.0, then you'll need a different syntax for the arrays:
$Pages = array(
'/clothes' => 'Clothes',
'/clothes/something.php' => 'Something'
);
$BreadCrumbs = array();
[EDIT]
OK, one last go:
<?php
$Pages = array(
'clothes' => 'Clothes',
'something' => 'Something'
);
$path = $_SERVER["PHP_SELF"];
$parts = explode('/',$path);
if (count($parts) < 2)
{
echo("home");
}
else
{
echo ("Home » ");
for ($i = 1; $i < count($parts); $i++)
{
if (!strstr($parts[$i],"."))
{
echo("<a href=\"");
for ($j = 0; $j <= $i; $j++) {echo $parts[$j]."/";};
echo("\">". str_replace('-', ' ', $Pages[$parts[$i]])."</a> » ");
}
else
{
$str = $parts[$i];
$pos = strrpos($str,".");
$parts[$i] = substr($str, 0, $pos);
echo str_replace('-', ' ', $Pages[$parts[$i]]);
};
};
};
?>

Why is this PHP script working in one subdomain and not another identical one? [duplicate]

This question already has an answer here:
Why identical PHP script might work in one subdomain and not another?
(1 answer)
Closed 8 years ago.
I have a php script that creates WordPress posts from a csv file ("file.csv") that is on the same subdomain as WordPress. This has been working for months, however, I just uploaded a new "file.csv" file to a couple of subdomains and the script is not working, resulting in a blank screen and does not create posts.
To troubleshoot, I checked other subdomains where I have the php script set up and uploaded the new "file.csv" file. It worked there.
So, on some subdomains the script is working and on some it is not. The WordPress installs are identical. The php script is identical, I downloaded and uploaded it from one domain to the other to troubleshoot. It works on one and not the other. I have tried identical "file.csv", still works on one subdomain and not the other.
The below error comes up in the error logs
[17-Nov-2013 11:00:05] PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 8388608 bytes) in /filepath/_adder.php on line 16
However the "file.csv" file is identical in both installs, and is the same size. But it still works in one and not the other.
Why might the script be working correctly on done subdomain and not the other? Any suggestions, things to try or tips would be very much appreciated.
For sake of completeness, below is the php script in question.
<?php
require_once('wp-config.php');
$siteurl = get_site_url();
function clearer($str) {
//$str = iconv("UTF-8", "UTF-8//IGNORE", $str);
$str = utf8_encode($str);
$str = str_replace("’", "'", $str);
$str = str_replace("–", "-", $str);
return htmlspecialchars($str);
}
//file read
if(file_exists("file.csv")) $csv_lines = file("file.csv");
if(is_array($csv_lines)) {
$cnt = 15;
for($i = 0; $i < $cnt; $i++) {
$line = $csv_lines[$i];
$line = trim($line);
$first_char = true;
$col_num = 0;
$length = strlen($line);
for($b = 0; $b < $length; $b++) {
if($skip_char != true) {
$process = true;
if($first_char == true) {
if($line[$b] == '"') {
$terminator = '",';
$process = false;
}else
$terminator = ',';
$first_char = false;
}
if($line[$b] == '"'){
$next_char = $line[$b + 1];
if($next_char == '"')
$skip_char = true;
elseif($next_char == ',') {
if($terminator == '",') {
$first_char = true;
$process = false;
$skip_char = true;
}
}
}
if($process == true){
if($line[$b] == ',') {
if($terminator == ',') {
$first_char = true;
$process = false;
}
}
}
if($process == true)
$column .= $line[$b];
if($b == ($length - 1)) {
$first_char = true;
}
if($first_char == true) {
$values[$i][$col_num] = $column;
$column = '';
$col_num++;
}
}
else
$skip_char = false;
}
}
$values = array_values($values);
//print_r($values);
/*************************************************/
if(is_array($values)) {
//file.csv read
for($i = 0; $i < count($values); $i++) {
unset($post);
//check duplicate
//$wpdb->show_errors();
$wpdb->query("SELECT `ID` FROM `" . $wpdb->prefix . "posts`
WHERE `post_title` = '".clearer($values[$i][0])."' AND `post_status` = 'publish'");
//echo $wpdb->num_rows;
if($values[$i][0] != "Name" && $values[$i][0] != "" && $wpdb->num_rows == 0) {
$post['name'] = clearer($values[$i][0]);
$post['Address'] = clearer($values[$i][1]);
$post['City'] = clearer($values[$i][2]);
$post['Categories'] = $values[$i][3];
$post['Tags'] = $values[$i][4];
$post['Top_image'] = $values[$i][5];
$post['Body_text'] = clearer($values[$i][6]);
//details
for($k = 7; $k <= 56; $k++) {
$values[$i][$k] != '' ? $post['details'] .= "<em>".clearer($values[$i][$k])."</em>\r\n" : '';
}
//cats
$categoryes = explode(";", $post['Categories']);
foreach($categoryes AS $category_name) {
$term = term_exists($category_name, 'category');
if (is_array($term)) {
//category exist
$cats[] = $term['term_id'];
}else{
//add category
wp_insert_term( $category_name, 'category' );
$term = term_exists($category_name, 'category');
$cats[] = $term['term_id'];
}
}
//top image
if($post['Top_image'] != "") {
$im_name = md5($post['Top_image']).'.jpg';
$im = #imagecreatefromjpeg($post['Top_image']);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['topimage'] = '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
//bottom images
for($k = 57; $k <= 76; $k++) {
if($values[$i][$k] != '') {
$im_name = md5($values[$i][$k]).'.jpg';
$im = #imagecreatefromjpeg($values[$i][$k]);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['images'] .= '<a href="'.$siteurl.'/images/'.$im_name.'"><img class="alignnone size-full"
src="'.$siteurl.'/images/'.$im_name.'" alt="" /></a>';
}
}
}
$post = array_map( 'stripslashes_deep', $post );
//print_r($post);
//post created
$my_post = array (
'post_title' => $post['name'],
'post_content' => '
<em>Address: '.$post['Address'].'</em>
'.$post['topimage'].'
'.$post['Body_text'].'
<!--more-->
'.$post['details'].'
'.$post['images'].'
',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $cats
);
unset($cats);
//add post
//echo "ID:" .
$postid = wp_insert_post($my_post); //post ID
//tags
wp_set_post_tags( $postid, str_replace(';',',',$post['Tags']), true ); //tags
echo $post['name']. ' - added. ';
//google coords
$address = preg_replace("!\((.*?)\)!si", " ", $post['Address']).', '.$post['City'];
$json = json_decode(file_get_contents('http://hicon.by/temp/googlegeo.php?address='.urlencode($address)));
//print_r($json);
if($json->status == "OK") {
//нашло адрес
$google['status'] = $json->status;
$params = $json->results[0]->address_components;
if(is_array($params)) {
foreach($params AS $id => $p) {
if($p->types[0] == 'locality') $google['locality_name'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_2') $google['sub_admin_code'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_1') $google['admin_code'] = $p->short_name;
if($p->types[0] == 'country') $google['country_code'] = $p->short_name;
if($p->types[0] == 'postal_code') $google['postal_code'] = $p->short_name;
}
}
$google['address'] = $json->results[0]->formatted_address;
$google['location']['lat'] = $json->results[0]->geometry->location->lat;
$google['location']['lng'] = $json->results[0]->geometry->location->lng;
//print_r($params);
//print_r($google);
//insert into DB
$insert_code = $wpdb->insert( $wpdb->prefix . 'geo_mashup_locations',
array( 'lat' => $google['location']['lat'], 'lng' =>
$google['location']['lng'], 'address' => $google['address'],
'saved_name' => $post['name'], 'postal_code' => $google['postal_code'],
'country_code' => $google['country_code'], 'admin_code' =>
$google['admin_code'],
'sub_admin_code' => $google['sub_admin_code'], 'locality_name' =>
$google['locality_name'] ),
array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
);
if($insert_code) {
$google_code_id = $wpdb->insert_id;
$geo_date = date( 'Y-m-d H:i:s' );
$wpdb->insert(
$wpdb->prefix . 'geo_mashup_location_relationships',
array( 'object_name' => 'post', 'object_id' => $postid, 'location_id' => $google_code_id, 'geo_date' =>
$geo_date ),
array( '%s', '%s', '%s', '%s' )
);
}else{
//can't insert data
}
echo ' address added.<br />';
}else{
//echo $json->status;
}
}
} //$values end (for)
}
}else{
//not found file.csv
echo 'not found file.csv';
}
$input = explode("\n", file_get_contents("file.csv"));
foreach ($input as $line) {
// process all lines.
}
// This function removes first $CNT elements.
// More info:
// http://php.net/manual/en/function.array-slice.php
$output = array_slice($input, $cnt);
file_put_contents("file.csv", implode("\n", $output));
?>
<html>
<body>
<form enctype="multipart/form-data" method="post">
CSV: <input name="file" type="file" />
<input type="submit" value="Send File" />
</form>
</body>
</html>
Your imported file is larger than limit allowed on the server. You are importing the large chuck of data and storing in Memory that is causing crashing. There are two ways to stop crashing.
1.You can put at the top of you code before any other thing written which give larger access to memory.
ini_set('memory_limit','256M');
2.You read the file line by line and process according to that.
My suggestion is to go for 2nd way and there are two reasons for suggestion.
As what will you do if the size increases beyond possible to keep the file memory. Either you have to split it or go for second option, so why don't you start with second options rather using at later stage.
Second Reason is Memory Allocation and Speed of Execution. If you adopt the second option the Memory will be less occupied and your program will execute faster than the reading full file in Memory then doing work on it.

how to get text from pdf file and save it into DB [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php: pdf to string
i am trying to save text content of pdf file in to DB. I found this link helpful Converting PDF to string, and worked on it. But it only converts very less amount of data :( why is it so ?
Or any other solution on how to convert complex pdf file (containing header, footer, tables, nd two column layout in some pages etc etc.) in to string and save it to DB ?
A long time ago i wrote a script which download a pdf and convert it into text. This function do the convertion:
function pdf2string($sourcefile) {
$content = $sourcefile;
$searchstart = 'stream';
$searchend = 'endstream';
$pdfText = '';
$pos = 0;
$pos2 = 0;
$startpos = 0;
while ($pos !== false && $pos2 !== false) {
$pos = strpos($content, $searchstart, $startpos);
$pos2 = strpos($content, $searchend, $startpos + 1);
if ($pos !== false && $pos2 !== false){
if ($content[$pos] == 0x0d && $content[$pos + 1] == 0x0a) {
$pos += 2;
} else if ($content[$pos] == 0x0a) {
$pos++;
}
if ($content[$pos2 - 2] == 0x0d && $content[$pos2 - 1] == 0x0a) {
$pos2 -= 2;
} else if ($content[$pos2 - 1] == 0x0a) {
$pos2--;
}
$textsection = substr(
$content,
$pos + strlen($searchstart) + 2,
$pos2 - $pos - strlen($searchstart) - 1
);
$data = gzuncompress($textsection);
$pdfText .= pdfExtractText($data);
$startpos = $pos2 + strlen($searchend) - 1;
}
}
return preg_replace('/(\s)+/', ' ', $pdfText);
}
EDIT: I call pdfExtractText() This function is defined here:
function pdfExtractText($psData){
if (!is_string($psData)) {
return '';
}
$text = '';
// Handle brackets in the text stream that could be mistaken for
// the end of a text field. I'm sure you can do this as part of the
// regular expression, but my skills aren't good enough yet.
$psData = str_replace('\)', '##ENDBRACKET##', $psData);
$psData = str_replace('\]', '##ENDSBRACKET##', $psData);
preg_match_all(
'/(T[wdcm*])[\s]*(\[([^\]]*)\]|\(([^\)]*)\))[\s]*Tj/si',
$psData,
$matches
);
for ($i = 0; $i < sizeof($matches[0]); $i++) {
if ($matches[3][$i] != '') {
// Run another match over the contents.
preg_match_all('/\(([^)]*)\)/si', $matches[3][$i], $subMatches);
foreach ($subMatches[1] as $subMatch) {
$text .= $subMatch;
}
} else if ($matches[4][$i] != '') {
$text .= ($matches[1][$i] == 'Tc' ? ' ' : '') . $matches[4][$i];
}
}
// Translate special characters and put back brackets.
$trans = array(
'...' => '…',
'\205' => '…',
'\221' => chr(145),
'\222' => chr(146),
'\223' => chr(147),
'\224' => chr(148),
'\226' => '-',
'\267' => '•',
'\374' => 'ü',
'\344' => 'ä',
'\247' => '§',
'\366' => 'ö',
'\337' => 'ß',
'\334' => 'Ü',
'\326' => 'Ö',
'\304' => 'Ä',
'\(' => '(',
'\[' => '[',
'##ENDBRACKET##' => ')',
'##ENDSBRACKET##' => ']',
chr(133) => '-',
chr(141) => chr(147),
chr(142) => chr(148),
chr(143) => chr(145),
chr(144) => chr(146),
);
$text = strtr($text, $trans);
return $text;
}
EDIT2: To get content from a local file use:
$fp = fopen($sourcefile, 'rb');
$content = fread($fp, filesize($sourcefile));
fclose($fp);
EDIT3: Before saving data to db i use an escape function:
function escape($str)
{
$search=array("\\","\0","\n","\r","\x1a","'",'"');
$replace=array("\\\\","\\0","\\n","\\r","\Z","\'",'\"');
return str_replace($search,$replace,$str);
}

How to trim white spaces of array values in php

I have an array as follows
$fruit = array(' apple ','banana ', ' , ', ' cranberry ');
I want an array which contains the values without the white spaces on either sides but it can contain empty values how to do this in php.the output array should be like this
$fruit = array('apple','banana', ',', 'cranberry');
array_map and trim can do the job
$trimmed_array = array_map('trim', $fruit);
print_r($trimmed_array);
Multidimensional-proof solution:
array_walk_recursive($array, function(&$arrValue, $arrKey){ $arrValue = trim($arrValue);});
array_walk() can be used with trim() to trim array
<?php
function trim_value(&$value)
{
$value = trim($value);
}
$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
?>
See 2nd example at http://www.php.net/manual/en/function.trim.php
I had trouble with the existing answers when using multidimensional arrays. This solution works for me.
if (is_array($array)) {
foreach ($array as $key => $val) {
$array[$key] = trim($val);
}
}
If the array is multidimensional, this will work great:
//trims empty spaces in array elements (recursively trim multidimesional arrays)
function trimData($data){
if($data == null)
return null;
if(is_array($data)){
return array_map('trimData', $data);
}else return trim($data);
}
one sample test is like this:
$arr=[" aaa ", " b ", "m ", [" .e ", " 12 3", "9 0 0 0 "]];
print_r(trimData($arr));
//RESULT
//Array ( [0] => aaa [1] => b [2] => m [3] => Array ( [0] => .e [1] => 12 3 [2] => 9 0 0 0 ) )
$fruit= array_map('trim', $fruit);
array_map('trim', $data) would convert all subarrays into null. If it is needed to trim spaces only for strings and leave other types as it is, you can use:
$data = array_map(
function ($item) {
return is_string($item) ? trim($item) : $item;
},
$data
);
If you want to trim and print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:
foreach($array as $key => $value)
{
$array[$key] = trim($value);
print("-");
print($array[$key]);
print("-");
print("<br>");
}
If you want to trim but do not want to print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:
$array = array_map('trim', $array);
If you don't want to lose elements of an associative array, DONT use array_walk or array_map!
A slightly shorter version of the foreach solution:
foreach($array as &$val)
$val = trim($val);
This works for associative arrays.
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function generateRandomSpaces() {
$output = '';
$i = rand(1, 10);
for ($j = 0; $j <= $i; $j++) {
$output .= " ";
}
return $output;
}
// Generating an array to test
$array = [];
for ($i = 0; $i <= 1000; $i++) {
$array[] = generateRandomSpaces() . generateRandomString(10) . generateRandomSpaces();
}
// ARRAY MAP
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
$trimmed_array=array_map('trim',$array);
}
$time = (microtime(true) - $start);
echo "Array map: " . $time . " seconds\n";
// ARRAY WALK
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
array_walk($array, 'trim');
}
$time = (microtime(true) - $start);
echo "Array walk : " . $time . " seconds\n";
// FOREACH
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
foreach ($array as $index => $elem) {
$array[$index] = trim($elem);
}
}
$time = (microtime(true) - $start);
echo "Foreach: " . $time . " seconds\n";
// FOR
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
for ($j = 0; $j < count($array) - 1; $j++) {
$array[$j] = trim($array[$j]);
}
}
$time = (microtime(true) - $start);
echo "For: " . $time . " seconds\n";
The output of the code above is:
Array map: 8.6775720119476 seconds
Array walk: 10.423238992691 seconds
Foreach: 7.3502039909363 seconds
For: 9.8266389369965 seconds
This values of course may change but I would say foreach is the best option.
Trim in array_map change type if you have NULL in value.
Better way to do it:
$result = array_map(function($v){
return is_string($v)?trim($v):$v;
}, $array);
simply you can use regex to trim all spaces or minify your array items
$array = array_map(function ($item) {
return preg_replace('/\s+/', '', $item);
}, $array);
function trim_value(&$value)
{
$value = trim($value);
}
// ut_sreco_dis Module
public function disExcelUpload($file=""){
ini_set('MAX_EXECUTION_TIME', -1);
ini_set('memory_limit', '-1');
$file_upload = $file;
if (isset($file_upload) && !empty($file_upload)){
//You can add directly the Composer Autoloder in your controller:
require FCPATH . 'vendor/autoload.php';
try{
$objPHPExcel = PHPExcel_IOFactory::load($file_upload);
}
catch (Exception $e){
die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.#$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$highestco = $sheet->getHighestDataColumn();
$arrayCount = count($allDataInSheet);
$now = date("Y-m-d H:i:s");
$flag = 0;
$check_template = array(
'A' => 'FIN_ID',
'B' => 'SECCODE',
'C' => 'SCHEME_NO',
'D' => 'SEC_SCH',
'E' => 'DISNO',
'F' => 'DISQTY',
'G' => 'BILLQTY',
'H' => 'BILLREF',
'I' => 'BILLDT',
);
$input_template = $allDataInSheet[1];
array_walk($input_template, $this->trim_value);
$result = array_diff($check_template, $input_template);
if(empty($result))
{
$this->srObject->truncTableDis();
# loop for inserting data
for ($i = 2,$j=0; $i <= $highestRow; $i++){
$db_ch_ot = 64;
$fin_id = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_code = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sch_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_sch = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_ref = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_dt = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
if(empty($bill_dt)){
$bill_dt = null;
}else{
$dip_dt = date("Y-m-d",strtotime($bill_dt));
}
$dt = date('Y-m-d H:i:s');
$insert_data = array(
"fin_id_data" => $fin_id,
"sec_code_data" => $sec_code,
"sch_no_data" => $sch_no,
"sec_sch_data" => $sec_sch,
"dis_no_data" => $dis_no,
"dis_qty_data" => $dis_qty,
"bill_qty_data" => $bill_qty,
"bill_ref_data" => $bill_ref,
"bill_dt_data" => $bill_dt,
"created_at_data" => $dt,
"updated_at_data" => $dt,
);
if($this->srObject->insertSdisData($insert_data))
{
++$flag;
}
} //loop close
} else {
$this->session->set_flashdata('error', 'Error. Invalid Excel Template');
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
$this->session->set_flashdata('success', 'File Uploaded Successfully ..'.' New Record Inserted : '.$flag);
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
}
function trim_value(&$value)
{
$value = trim($value);
}
// ut_sreco_dis Module
public function disExcelUpload($file=""){
ini_set('MAX_EXECUTION_TIME', -1);
ini_set('memory_limit', '-1');
$file_upload = $file;
if (isset($file_upload) && !empty($file_upload)){
//You can add directly the Composer Autoloder in your controller:
require FCPATH . 'vendor/autoload.php';
try{
$objPHPExcel = PHPExcel_IOFactory::load($file_upload);
}
catch (Exception $e){
die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.#$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$highestco = $sheet->getHighestDataColumn();
$arrayCount = count($allDataInSheet);
$now = date("Y-m-d H:i:s");
$flag = 0;
$check_template = array(
'A' => 'FIN_ID',
'B' => 'SECCODE',
'C' => 'SCHEME_NO',
'D' => 'SEC_SCH',
'E' => 'DISNO',
'F' => 'DISQTY',
'G' => 'BILLQTY',
'H' => 'BILLREF',
'I' => 'BILLDT',
);
$input_template = $allDataInSheet[1];
array_walk($input_template, $this->trim_value);
$result = array_diff($check_template, $input_template);
if(empty($result))
{
$this->srObject->truncTableDis();
# loop for inserting data
for ($i = 2,$j=0; $i <= $highestRow; $i++){
$db_ch_ot = 64;
$fin_id = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_code = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sch_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_sch = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_ref = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_dt = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
if(empty($bill_dt)){
$bill_dt = null;
}else{
$dip_dt = date("Y-m-d",strtotime($bill_dt));
}
$dt = date('Y-m-d H:i:s');
$insert_data = array(
"fin_id_data" => $fin_id,
"sec_code_data" => $sec_code,
"sch_no_data" => $sch_no,
"sec_sch_data" => $sec_sch,
"dis_no_data" => $dis_no,
"dis_qty_data" => $dis_qty,
"bill_qty_data" => $bill_qty,
"bill_ref_data" => $bill_ref,
"bill_dt_data" => $bill_dt,
"created_at_data" => $dt,
"updated_at_data" => $dt,
);
if($this->srObject->insertSdisData($insert_data))
{
++$flag;
}
} //loop close
} else {
$this->session->set_flashdata('error', 'Error. Invalid Excel Template');
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
$this->session->set_flashdata('success', 'File Uploaded Successfully ..'.' New Record Inserted : '.$flag);
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
}
function trimArray(&$value)
{
$value = trim($value);
}
$pmcArray = array('php ','mysql ', ' code ');
array_walk($pmcArray, 'trimArray');
by using array_walk function, we can remove space from array elements and elements return the result in same array.

Categories