I can't solve a problem occurring when I try to export an array to a CSV file. I have used this function several times without problem but here I do not see where my mistake is.
I set an array:
$mytags= array();
I populate it by a loop. When I print the content through print_r($mytags);
it seems to be OK, here some examples of my output:
Array ( [0] => [1] => air-travel [2] => airports [3] => security-airport [4] => city-airport ... )
After that I try to export the result to CSV by fputcsv:
$fp = fopen('file.csv', 'w');
foreach ($mytags as $fields) {
fputcsv($fp, $fields);
}
But I get this error:
Warning: fputcsv() expects parameter 2 to be array, string given in
C:\wamp\www\tests\capturetags.php on line 55
Could the problem be that there is only one field?
Alternatively, I tried to replace $fields by $mytags to write the CSV, and in this case I get a 4GB files, so it's not the
Does someone see how to record thhis unique field in a CSV file?
The error is very clear, $fields is not an array, it is a string. You need an array.
fputcsv($fp, $mytags);
Without a foreach loop will do the job.
Related
Thank you for the response. I will give it a try and update my question, I have my own code but it is a bit messy to show all. My problem is that I do not get the indexes right.
I use:
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$products[$key] = str_getcsv($value);
}
And I manage to read the data, but this will give me an error:
if ((int)$products[$_sku] > 0 && isset($products[$_sku])) {
Error: Notice: Undefined index: test-product-1 in....
The 'test-product-1' is from the sku column in the csv file
Output from
echo '<pre>';
print_r($products);
echo '</pre>';
gives:
Array
(
[0] => Array
(
[0] => sku
[1] => qty
)
[1] => Array
(
[0] => test-product-1
[1] => 3
)
[2] => Array
(
[0] => test-product-2
[1] => 6
)
[3] => Array
(
[0] => test-product-3
[1] => 30
)
)
I am trying to use a csv file to be imported into the array to replace
$products = [
'test-product-1' => 3,
'test-product-2' => 6,
'test-product-3' => 30
];
But I can not produce the same array when I import from the CSV file, which will cause problems. Examples for CSV to array: http://php.net/manual/en/function.str-getcsv.php
CSV file:
sku,qty
test-product-1,3
test-product-2,6
test-product-3,30
Next step is to extend the script to handle prices. I need to be able to pick up these variables from the CSV file too. And use them inside the for loop.
sku,qty,price,special_price
test-product-1,3,100,50
test-product-2,6,99,
test-product-3,30,500,300
I think the problem is that when you store the row, your storing it indexed by the row number ($key will be the line number in the file). Instead I think you want to index it by the first column of the CSV file. So extract the data first (using str_getcsv() as you do already) and index by the first column ([0])...
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $value)
{
$data = str_getcsv($value);
$products[$data[0]] = $data;
}
If you want to add the first row as a header and use it to key the data...
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
$headers = str_getcsv(array_shift($lines));
$products = array();
foreach ( $lines as $value ) {
$data = str_getcsv($value);
$products[$data[0]] = array_combine($headers, $data);
}
The removes the first row of the array using array_shift() and then uses this row in the array_combine() as the keys for each row. With your test data, you would get something like...
Array
(
[test-product-1] => Array
(
[sku] => test-product-1
[qty] => 3
[price] => 100
[special_price] => 50
)
I used following code in my project and its working fine for me.
I used csv_reader PHP library for it.
You have to put this library in your library folder and import it into file where you want to read your csv.
include_once('../csv_reader.php');
$read = new CSV_Reader;
$read->strFilePath = "file_name_with_path";
$read->strOutPutMode = 0; // 1 will show as HTML 0 will return an array
$read->setDefaultConfiguration();
$read->readTheCsv();
$dataArr = array();
$dataArr = $read->arrOutPut;
In $dataArr, i will get the result,
I have a php file that contains text in the following format.
line 1 - "Title","URL","imgURL","tags"
line 2 - "Title","URL","imgURL","tags"
line 3 - "Title","URL","imgURL","tags"
It is basically structured like a database so each line is a record and 1st set of "" is always a title. 2nd set of "" is always a URL, etc.... line by line.
I'm not an experienced programmer by any stretch of the imagination. What is the best way to create an array from the contents of the file?
I've tried the following, but it didn't work.
$content = array(file_get_contents("path/content.php"));
I believe I need to update the structure of the data and the method I use to create the array, but I'm not sure how. Any help is greatly appreciated.
I want to be able to retrieve title, URL, imgURL, or tags from any line of text, but I don't know how to express that in an array format.
I think I want to be able to request $content[0][1] to get the URL from line1 and $content[1][3] to get the tags from line2.
$file = fopen("path/content.php", "r");
while($content[] = fgetcsv($file, 1000, ","));
You should then be able to access each element as you specified:
echo $content[0][1]; // echos first line, url
The format of your file is called CSV (comma separated values). Using PHP, you can parse a CSV file using the function fgetcsv: http://php.net/manual/en/function.fgetcsv.php
Are you looking for something like this?
/**
* Decodes a full CSV file to an array.
*
* #param string $file File to decode
*
* #throws \Exception
*
* #return array[]
*/
function csv_decode($file) {
$fh = fopen($file, 'r');
if($fh === false)
{
// FIXME: You should replace this with your own exception!
throw new \Exception("Failed to open file '$file' for reading");
}
$rows = [];
while ($row = fgetcsv($fh))
{
$rows[] = $row;
}
return $rows;
}
The format you have encountered is known as CSV (which stands for comma-separated values)
The above function decodes your data to an array with the structure you've described as can be seen from the output of the following snippet when run on your example data:
print_r(csv_decode('values.txt'));
Which outputs:
Array
(
[0] => Array
(
[0] => Title
[1] => URL
[2] => imgURL
[3] => tags
)
[1] => Array
(
[0] => Title
[1] => URL
[2] => imgURL
[3] => tags
)
[2] => Array
(
[0] => Title
[1] => URL
[2] => imgURL
[3] => tags
)
)
I currently have a query that returns the array below.. When I try to export the data to a CSV file I see the data twice (The columns are repeted, not the rows).. Can someone explain to my why? (I want to have each records show only once)
Array
(
[0] => Array
(
[0] => 6991
[id] => 6991
[1] => 8588
[work_num] => 8588
[2] => Test123
[name] => Test123
[3] => 1407154
[deployed] => 1407154
[4] => 2015-10-13
[created_date] => 2015-10-13
)
)
This is the code that I am using to export the data
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('id','Work Number','Name','Deployed','Date'));
$get_data = $CLASSNAME->FuntionName(Parameters);
foreach($get_data as $data_row) {
fputcsv($output, $data_row);
}
fclose($output);
If you are using MySQL, then replace mysql_fetch_array to mysql_fetch_row.
mysql_fetch_array returns result set as both numeric and associative array.
mysql_fetch_row will return result set as only numeric array.
Either fix your incoming data (when using PDO, use PDO::FETCH_ASSOC or PDO::FETCH_NUM instead of PDO::FETCH_BOTH, which is default) or name your columns when putting to csv:
foreach($get_data as $data_row) {
fputcsv($output, array(
$data_row['id'],
$data_row['work_num'],
$data_row['name'],
$data_row['deployed'],
$data_row['created_date']
));
}
I have a .csv template I'd wish for people to fill up, save it and upload it.
The problem is this, assuming some users would insert hidden line breaks in a row, when using fgetcsv() it would output the row broken by the hidden line breaks.
How can I escape the line break or sanitize my data?
Possible solution:
assume first row is correct, $count = count the number of delimiters until line break, the rebuild the text into an array as long as $count;
but i think the're better options available.
LATER EDIT
Here's the input *IMPORTANT[ ! ] : the data inside the excel file is "fine", it isn't broken, it's a single row!!! saving it as a csv file and opening it in notepad shows the following
asd;"asd
asd
asd";asd;asd
Here's the code
$handle = fopen("file.csv","r");
$data = fgetcsv($handle,";");
while($data = fgetcsv($handle)) {
$array = explode(";",$data[0]);
print_r($array);
}
fclose($handle);
Here's the echoed data
Array ( [0] => asd [1] => "asd ) Array ( [0] => asd ) Array ( [0] => asd" [1] => asd [2] => asd [3] => )
Thanks
it is very easy to test your case and see that there are no broken rows, if fields being properly quoted.
So, a CSV line like this
1,"joe
""Big Coyote""
Hopkins",598600
will be read with not a single problem.
I'm trying to store an array ($temp) into the $data array, where key is prices.
$data['prices'] = $temp;
However, PHP converts the array into string instead and is throwing me and error.
Notice: Array to string conversion
Is $data = array('prices' => $temp); the only solution?
edit:
I found my mistake. Yes, $data was used previously as a string that's why PHP is converting the input into string.
Problem 2, doing a print_r on $data['prices'] = $xml->result->Prices->Price, shows only 1 set of array. But I am able to retrive 2 sets of result by doing a foreach loop on $data['prices']. Why is that so?
Content of $temp http://pastebin.com/ZrmnKUPB
Let me be more clear..
The full xml object I'm trying to extract information from: http://pastebin.com/AuMJiyrw
I'm only interested in the price array (Price_strCode and Price_strDescription) and store them in $data['prices']. End result something like this:
Array(
[0] => (
[Price_strCode] => 0001
[Price_strDescription] => Gold
)
[1] => (
[Price_strCode] => 0002
[Price_strDescription] => Silver
)
)
Unless you are doing some other array to string conversion elsewhere, the array is actually being stored as another array.
$data['prices'] will be an array, which can be accessed as $data['prices']['key'].
This is not possible, I have been doing this always and it works fine. You must be doing something else somewhere which is causing your array to convert to strong. share your code here