I use the parser for converting xls to csv http://code.google.com/p/php-excel-reader/
<?php
set_time_limit(300);
require_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader("file.xls", false, 'UTF-8');
$f = fopen('file.csv', 'w');
for($row = 1; $row <= $data->rowcount(); $row++)
{
$out = '';
for($col = 1; $col <= $data->colcount(); $col++)
{
$val = $data->val($row,$col);
// escape " and \ characters inside the cell
$escaped = preg_replace(array('#”#u', '#\\\\#u', '#[”"]#u'), array('"', '\\\\\\\\', '\"'), $val);
if(empty($val))
$out .= ',';
else
$out .= '"' . $escaped . '",';
}
// remove last comma (,)
fwrite($f, substr($out, 0, -1));
fwrite($f, "\n");
}
fclose($f);
?>
From some strange reason it skip cells with specials symbols - like ° or ®. How it can be fixed?
utf8_decode and html_entity_decode works for me:
<?php
set_time_limit(300);
require_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader("file.xls", false, 'UTF-8');
$f = fopen('file.csv', 'w');
for($row = 1; $row <= $data->rowcount(); $row++)
{
$out = '';
for($col = 1; $col <= $data->colcount(); $col++)
{
$val = $data->val($row,$col);
// escape " and \ characters inside the cell
$escaped = preg_replace(array('#”#u', '#\\\\#u', '#[”"]#u'), array('"', '\\\\\\\\', '\"'), $val);
$escaped = utf8_decode($escaped);
//$escaped = html_entity_decode($escaped);
if(empty($val))
$out .= ',';
else
$out .= '"' . $escaped . '",';
}
// remove last comma (,)
fwrite($f, substr($out, 0, -1));
fwrite($f, "\n");
}
fclose($f);
?>
Output:
"1","2","3","4","5"
"a","b","c","d","e"
"6","7","°","9","10"
"q","w","e","r","t"
"®","12","13","14","15"
"z","x","c","v","b"
Related
I've been trying to make the first letter of a string in the capital but I can't get it to work.
I have tried the following code:
<?php
$str = $_POST['Papier'];
$f = highlightKeywords('papierwaren', $str);
$s = strtolower($f);
$r = ucfirst($s);
function highlightKeywords($text, $keyword)
{
$pos = strpos($text, $keyword);
$wordsAry = explode(" ", $keyword);
$wordsCount = count($wordsAry);
for ($i = 0; $i < $wordsCount; $i++) {
if ($pos === false) {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . strtolower($wordsAry[$i]) . "</span>";
} else {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . $wordsAry[$i] . "</span>";
}
$text = str_ireplace($wordsAry[$i], $highlighted_text, $text);
}
return $text;
}
still, I am not getting it to work and I tried if whitespace occurs with the following
$r=ucfirst(trim($s));
still not succeeded. This 'papierwaren' text i'm getting it form db so pls someone help me to resolve this.
As Kaddath said, You are adding HTML to your string (<span ...). When you use ucfirst it changes the first char to uppercase but the first char is now <, the uppercase for < is <.
Try this code:
<?php
$str = 'papier';
$f = highlightKeywords('papierwaren', $str);
echo $f;
function highlightKeywords($text, $keyword)
{
$pos = strpos($text, $keyword);
$wordsAry = explode(" ", $keyword);
$wordsCount = count($wordsAry);
for ($i = 0; $i < $wordsCount; $i++) {
if ($pos === false) {
if ($i === 0) {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . ucfirst(strtolower($wordsAry[$i])) . "</span>";
} else {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . strtolower($wordsAry[$i]) . "</span>";
}
} else {
if ($i === 0) {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . ucfirst($wordsAry[$i]) . "</span>";
} else {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . $wordsAry[$i] . "</span>";
}
}
$text = str_ireplace($wordsAry[$i], $highlighted_text, $text);
}
return $text;
}
In laravel this should help
use Illuminate\Support\Str;
$testString = 'this is a sentence.';
$uppercased = Str::ucfirst($testString);
Do not forget to import Illuminate\Support\Str to controller.
$result = "";
while (some condition)
{
$result = file_get_contents("filename.txt");
$result = "$result\n" . $result;
file_put_contents("filename.txt", $result);
}
echo nl2br ($result);
I want to echo the first line as left aligned and second line as right aligned and so on on a web page. Is there any way to achieve this?
First you can split the text into an array buy using implode and use CSS to align them:
$result = "";
while (some condition){
$result = file_get_contents("filename.txt");
$result = "$result\n" . $result;
file_put_contents("filename.txt", $result);
}
$lines = implode('\n',$result);
echo "<div class='lines'>";
foreach($lines as $line){
echo $line;
}
echo "</div>";
// CSS:
echo '.lines > div:nth(even){ text-align:right; }';
$aLines = readfile(<file>);
for( $i = 0; $i < count( $aLines ); $i++ ) {
$align = ($i%2)?"left":"right";
echo "<div style='text-align: {$align}'>{$aLines[$i]}</div>";
}
Or if you meant to align inside the file itself:
$aLines = readfile(<source_file>);
$iLineWidth = 100;
$aLinesNew = [];
for( $i = 0; $i < count( $aLines ); $i++ ) {
$sLine = ($i%2)?$aLines[$i]:str_pad( $aLines[$i], $iLineWidth, " ", STR_PAD_LEFT);
$sLine = trim($sLine);
array_push( $aLinesNew, $sLine );
}
file_put_contents( <destination_file>, implode( "\n", $aLinesNew ) );
I have code to export mysql query result data into Excel. But Now I use SQL Server.I haven't idea to fetch number of fields name. I find many blogs but they all are display php function of mysql database. I need php function which usefull to get field name and number from SQL Query Result
$header = '';
$result = '';
$exportData = sqlsrv_query($gaSql['link'], $sQuery) or die("$sQuery: " . sqlsrv_errors());
$fields = mysql_num_fields($exportData);
for ($i = 0; $i < $fields; $i++) {
if (in_array(mysql_field_name($exportData, $i), $_POST['optFieldName'])) {
$header .= mysql_field_name($exportData, $i) . "\t";
}
// $header .= mysql_field_name($exportData, $i) . "\t";
}
//
$row = array();
for ($i = 0; $i < mysql_num_rows($exportData); $i++) {
$result_excel = mysql_fetch_array($exportData);
array_push($row, $result_excel);
}
foreach ($row as $rowvalue) {
$line = '';
for ($j = 0; $j < count($_POST['optFieldName']); $j++) {
$value = $rowvalue[$_POST['optFieldName'][$j]];
if ((!isset($value) ) || ( $value == "" )) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$result .= trim($line) . "\n";
}
$result = str_replace("\r", "", $result);
if ($result == "") {
$result = "\nNo Record(s) Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$result";
Would you please give me some guidance on how to style one character in a string at specific index? the index of this string comes from an array and in some cases the array is empty, so I only need to style the character in the string if the array is not empty
$indices = array(74, 266);
$string = "CAGGACACTCTTTCTAGTGTTGATTCACCTCGAAGAAGGTCTGGCCTATTAAGAGATCAAGTTCAGTTGGTAAAAAGAAGCAACTCTGCTCGTTATGAGATAGTCCCGATTCAAGATCAACTATCATTTGAGAAGGGTTTCTTTATTGTAATCCGTGCATGCCAGTTGTTGGCTCAGAAGAATGAAGGCATTGTACTGGTGGGAGTCGCTGGTCCTTCAGGGGCCGGAAAGACCATGTTTACAGAAAAGATCCTGAATGTTATGCCTAGTATTGCAATCATAAACATGGACAACTACAATGATCCCAGTCGTATCATTGATGGAAACTTCGACG";
so how do I add a surround the character at the index 74 and 266 with a span so I can give it a different style?
my data is coming from the database so I need to make it dynamic.
Thanks
It's fairly easy: all you need is a few substrs in a loop and to keep track of the character count.
Here's a working code I made:
// zero-based indices
$indices = array(3, 10, 25);
// input
$in = 'abcDefghijKlmnopqrstuvwxyZ';
$openTag = '<b>';
$closeTag = '</b>';
$out = '';
$last = 0;
foreach($indices as $i) {
$fragment = substr($in, $last, $i-$last);
$letter = substr($in, $i, 1);
$last = $i+1;
$out .= $fragment . $openTag . $letter . $closeTag;
}
$out .= substr($in, $last);
// output
echo $out;
For this example, $out is abc<b>D</b>efghij<b>K</b>lmnopqrstuvwxy<b>Z</b>.
For convenience, here's it also as a function:
function highlightChars($text, $indices, $openTag, $closeTag) {
$out = '';
$last = 0;
foreach($indices as $i) {
$fragment = substr($text, $last, $i-$last);
$letter = substr($text, $i, 1);
$last = $i+1;
$out .= $fragment . $openTag . $letter . $closeTag;
}
$out .= substr($text, $last);
return $out;
}
I am trying to determine the end of a foreach loop that is seeded with a collection of DOMNodeList. Currently, I am using a for loop would like to avoid having a 'magic' number there. I do know there are only going to be 8 columns, but I would like the code me generic for other applications.
Is it possible to convert this to a Foreach loop? I have tried the end() and next() functions, but they are not returning any data and I suspect that they only work on arrays and not this DOMNodeList collection.
The code is building a CSV file without the trailing ','
Current output is:
"Value 1","Value 2","Value 3","Value 4","Value 5","Value 6","Value 7","Value 8"
Here is an example of code:
$cols = $row->getElementsByTagName("td");
$printData = true;
// Throw away the header row
if ($isFirst && $printData) {
$isFirst = false;
continue;
}
for ($i = 0; $i <= 8; $i++) {
$output = iconv("UTF-8", "ASCII//IGNORE", $cols->item($i)->nodeValue);
$output2 = trim($output);
if ($i == 8) {
// Last Column
echo "\"" . $output2 . "\"" . "\n";
} else {
echo "\"" . $output2 . "\"" . ",";
}
}
You can use:
$cols->length
To retrieve the number of items in a DOMNodeList.
See http://php.net/manual/en/class.domnodelist.php
Edit:
If you change you're code to this, you don't have to worry about the trailing comma, or the length:
$output = array();
foreach ($cols as $item) {
$output = iconv("UTF-8", "ASCII//IGNORE", $item->nodeValue);
$output2 = trim($output);
$output[] = '"' . $output2 . '"';
}
$outputstring = implode(',', $output);
$cols->length
Should give you the number of items in the list
for ($i = 0; $i < $cols->length; $i++) {
// ...
if ($i == $cols->length - 1) {
// last column