php fputcsv is trims the string value while writing to file - php

I don't know this question is asked or not. I didn't get his in suggestion.
I'm trying to write some data from database to an csv file.
I'm using fputcsv function.
I'm using following code :
$fh = #fopen($fileName, 'w+');
$writeText['sku'] = $somevalue
$writeText['attribute_set'] = $somevalue
$writeText['type'] = $somevalue
$writeText['default_catalogue_link']= $somevalue
$writeText['status'] = $somevalue
#fputcsv($fh, $writeText);
#flush();
#fclose($fh);
Some of the values starts with zero like $writeText['sku'] is 0987.
After writing to the file. I'm getting 987 in the file.
how to prevent this? I need with zero values.
Any help would be usefull.
Thanks in advance.

Are you using Excel to open the file? Because Excel interprets it as a number. Try open and see with a text editor.

Related

Encoding issue with PHP while writing in a .csv file

I'm working with a php array which contains some values parsed from a previous scraping process (using Simple HTML DOM Parser). I can normally print / echo the values of this array, which contains special chars é,à,è, etc. BUT, the problem is the following :
When I'm using fwrite to save values in a .csv file, some characters are not successfully saved. For example, Székesfehérvár is well displayed on my php view in HTML, but saved as Székesfehérvár in the .csv file which I generate with the php script above.
I've already set-up several things in the php script :
The page I'm scraping seems to be utf-8 encoded
My PHP script is also declared as utf-8 in the header
I've tried a lot of iconv and mb_encode methods in different places in the code
NOTE that when I'm make a JS console.log of my php array, using json_encode, the characters are also broken, maybe linked to the original encoding of the page I'm scraping?
Here's a part of the script, it is the part who is writing values in a .csv file
<?php
$data = array(
array("item1", "item2"),
array("item1", "item2"),
array("item1", "item2"),
array("item1", "item2")
// ...
);
//filename
$filename = 'myFileName.csv';
foreach($data as $line) {
$string_txt = ""; //declares the content of the .csv as a string
foreach($line as $item) {
//writes a new line of the .csv
$line_txt = "";
//each line of the .csv equals to the values of the php subarray, tab separated
$line_txt .= $item . "\t";
}
//PHP endline constant, indicates the next line of the .csv
$line_txt .= PHP_EOL;
//add the line to the string which is the global content of the .csv
$line_txt .= $string_txt;
}
//writing the string in a .csv file
$file = fopen($filename, 'w+');
fwrite($file, $string_txt);
fclose($file);
I am currently stuck because I can't save values with accentuated characters correctly.
Put this line in your code
header('Content-Type: text/html; charset=UTF-8');
Hope this helps you!
Try it
$file = fopen('myFileName.csv','w');
$data= array_map("utf8_decode", $data);
fputcsv($file,$data);
Excel has problems displaying utf8 encoded csv files. I saw this before. But you can try utf8 BOM. I tried it and works for me. This is simply adding these bytes at the start of your utf8 string:
$line_txt .= chr(239) . chr(187) . chr(191) . $item . "\t";
For more info:
Encoding a string as UTF-8 with BOM in PHP
Alternatively, you can use the file import feature in Excel and make sure the file origin says 65001 : Unicode(UTF8). It should display your text properly and you will need to save it as an Excel file to preserve the format.
The solution (provided by #misorude) :
When scraping HTML contents from webpages, there is a difference between what's displayed in your debug and what's really scraped in the script. I had to use html_entity_decode to let PHP interpret the true value of the HTML code I've scraped, and not the browser's interpretation.
To validate a good retriving of values before store them somewhere, you could try a console.log in JS to see if values are correctly drived :
PHP
//decoding numeric HTML entities who represents "Sóstói Stadion"
$b = html_entity_decode("Sóstói Stadion");
Javascript (to test):
<script>
var b = <?php echo json_encode($b) ;?>;
//print "Sóstói Stadion" correctly
console.log(b);
</script>

PHP get string from line number

I am using php to get the contents of a webpage:
$fileContent = file_get_contents('http://insertwebsitenamehere.com');
Is there a way to seek a line number andreturn the line at that location?
I know you can use SplFileObject::Seek if the fileContent is a file. Can I perform something similar without the need to turn it into a file?
You want file() instead
$fileContent = file('http://insertwebsitenamehere.com');
echo $fileContent[39]; //line 40

Read a csv file and create another csv file using php

I have a .csv file and when I open it via notepad it looks like:
ID501501503502
And when I print it in the browser via php, it looks like
ID 501 501 503 502
My code is:
$handle = fopen("MonC1.csv", "r");
$data = fgetcsv($handle, 0);
$fh = fopen('php://output', 'w');
if (! empty($data)) {
foreach ($data as $item) {
echo $item."<br>";
//fputcsv($fh, array($item));
}
}
So basically the br tag inside the for loop doesn't work.This is my first problem.
And the second problem is even if I use fputcsv(now it is turned off) it doesn't create a actual csv file.
Now my question is how come it has got no space in notepad and when I print in browser it gets space?
I have only one column and nothing else.
Any help is highly appreciated. Thanks in advance.
As mentioned in my comment, it looks like your original file is saved with UNIX line endings, and then you're using fgetcsv in Windows, so the whole file is being read as one line. There's probably one <br> at the end of the whole output.
So before processing your file, you'll need to preprocess it to convert the line endings.
On Linux, the utility unix2dos does what you want. Or, you can simply replace \n with \r\n in your file.
The other problem is that fgetcsv does not turn an entire file into an array. Instead, it reads a single line from your file handle, and converts that to an array. You'll need to read lines inside a loop:
while (($data = fgetcsv($handle)) !== FALSE) {
// $data contains one line of the CSV, in array form
// now you can fputcsv the single line
}

How to get a specific line with fgets() or fgetss()

I want to know how I would read a specific line (or even specific character) with fgets() or fgetss().
In example;
data.txt-
this is data 1
this is data 2
this is data 3
How would I read only data 2?
If it's possible, that is.
Also, how can I only read the last line? Like if I were to use a+ to write at the end of the file, it'd be the newest content.
Another question:
Is it possible to read through the whole file and check if something exists? If so, how?
Thanks in advance!
For text file:
$fileName = 'file.txt';
$file = new \SplFileObject($fileName);
$file->setFlags(\SplFileObject::READ_CSV);
$seek = 1;
$file->seek($seek);
$line = $file->fgets();
In $line variable has second line from file.

Writing large string to text file

A trivial use of PHP and frwite() to create/write to a text file.
However, is there a way to write a very large text string to a file using fwrite?()? I assume there is, and that it involves some form of buffer management. The PHP docs don't seem to have this covered.
Sample code:
$p = "Some really large string ~ 100-250K in size"
$myFile = "testp.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
set_file_buffer($fh, 1000000);
fwrite($fh, $p);
fclose($fh);
Believe it or not, this simply gets a file with the name of the file inside the file.
Using a much smaller text string, it works as expected. Pointers to what I should do would be useful.
UPDATE:
Some of you are missing that I did try the above with a string of ~100K, and it didn't work. All I got in the output file was the name of the file!!!
thanks
::: 2ND UPDATE....
never mind.. the whole thing was user error... god i need a drink... or sleep!
thanks
php/fwrite works as i thought it would/should.. nothing to see here..!
There is no limit on how much data can be written to a stream (a file handle) in PHP and you do not need to fiddle with any buffers. Just write the data to the stream, done.

Categories