Output CSV to array - php

I am using WP Alchemy to create a meta box with multiple check boxes.
The trouble I'm having is, I have a csv list of academic courses that I want to create the check box options from. So I'm taking the csv turning it into an array that the boxes are made from. However with the code I have now, only the LAST line is created in the array.
<?php
$file_handle = fopen('curriculum.csv', 'r');
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(',', $line_of_text);
$items = array ($parts[2] .$parts[3], );
}
fclose($file_handle);
?>
<?php foreach ($items as $i => $item): ?>
<?php $mb->the_field('cb_ex3'); ?>
<!-- similar to test #2, the same thing can be accomplished by simply
adding array brackets "[]" to the name -->
<input type="checkbox" name="<?php $mb->the_name(); ?>[]" value="<?php echo $item; ?>"<?php $mb->the_checkbox_state($item); ?>/> <?php echo $item; ?><br/>
<?php endforeach; ?>
So out of the few hundred lines of code, all I get is the last line.
Here is the actually file I'm working with: http://www.ouhsd.k12.ca.us/educational_services/curriculum/curriculum.csv

In each iteration of the loop you replace $items when you want to add to it, thus it only having the last value.
Also http://php.net/fgetcsv might be of some use to you.

You should be using the fgetcsv() (docs) function rather than trying to make sense of the CSV data yourself. Also, you should build the $items array (rather than overwriting it) as you loop over the file, adding a new item each time.
$file_handle = fopen('curriculum.csv', 'r');
fgets($file_handle); // this skips the csv header line
while (($parts = fgetcsv($file_handle)) !== FALSE) {
$items[] = $parts[2] . ' ' . $parts[3];
}
fclose($file_handle);
foreach ($items as $item) {
// Your HTML code goes here
echo $item . PHP_EOL;
}
Bonus points (you'll look cooler, using objects and iterators!)
$file = new SplFileObject('curriculum.csv');
$file->setFlags(SplFileObject::READ_CSV);
foreach (new LimitIterator($file, 1) as $parts) {
$items[] = $parts[2] . ' ' . $parts[3];
}
foreach ($items as $item) {
// Your HTML code goes here
echo $item . PHP_EOL;
}

items should be an array in your case. Initialize it outside the while loop
$items = array();
And then inside the while loop
$items[] = array ($parts[2] .$parts[3], );
should work.
Also look at fgetcsv as well as suggested.

You need an extra dimenson to your array.
$i=0;
$items= new array(); // i think you need this for some fun reason
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(',', $line_of_text);
$items[$i] = array ($parts[2] .$parts[3], );
}

You are overwriting the $items array. I would like to suggest a much simpler method to
<code><pre><?php
// in one step, load the datafile as an array, and loop over each line
// then explode the line by comma, and add to $lines array
foreach(file('curriculum.csv') as $line)
$lines[] = explode(',',$line);
// display the structure of the captured data
print_r($lines);
?></pre></code>
I think once you understand the structure of the captured data here, you can use the values as you wish in your output loop.
code, pre and php tags added for convenience

Related

Read Files from directory and echo certain line

I want to read all files from a directory but instead of displaying the first character i want to display a certain line, f.e. line 4.
<?php
$directory = "content/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode("|", $contents);
foreach ($items as $item) {
echo "$item[0]";
}
}
}
closedir($dir);
?>
Thanks!
You can use file() function. It reads files into an array, where every line will be an array member, to skip empty lines pass the FILE_SKIP_EMPTY_LINES flag paramater.
For more info consult the docs.
// `$items` is already an array
$items = explode("|", $contents);
// if you want first element of array just:
echo $item[0];
// if you want fourth element of array just:
echo $item[3];
// without `foreach`
Could you show your file structure, please?
Basicaly you can use something like this:
$contents = file_get_contents($filename);
$items = explode("\r\n", $contents); //explode file content
foreach ($items as $item) {
echo $item[3]; //echo your line
}

Sort array of file lines by alphabetical

I'm reading a text file of email addresses and outputting the domain only (with the # symbol). I need to alphabetize the list and then output to display on screen
Here is my code thus far:
<?php
$file_handle = fopen("file.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$parts = explode("#", $line);
$Id = $parts[count($parts) - 1];
echo "#" . $Id . "<br>";
}
fclose($file_handle);
?>
How can I initiate a sort to alphabetize the list?
This should work for you:
(Here I just get every line of the file with file(). Then I go through each line with array_map() where I only return the domain into the array $lines. At the end I sort the array with sort() and print it)
<?php
$lines = array_map(function($v){
return "#" . explode("#", $v)[1];
}, file("test.txt"));
sort($lines);
foreach($lines as $line)
echo $line . "<br />";
?>
Example input/output:
a.b#x.com
a.c#a.de
e.s#b.cu
#a.de
#b.cu
#x.com

How to get result to display properly (arrays)

I have created the code below and it all works completely fine my problem is that is will add as it goes along and display everything whereas i just need the last array element i have tried array_pop and the end function to no avail any ides?
$Count = 0;
$file_handle = fopen("test2.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(' ', $line_of_text);
$arr = array($parts[8]);
for($i=0;$i<count($arr);){
$count = $count + $arr[$i]/1024;
$results= array($count);
}
echo '<p>';
print_r($results);
echo '</p>';
}
fclose($file_handle);
Try using end()
echo '<p>';
end($results);
echo '</p>';
Assuming your array is numeric, couldn't you simply only display the last element like this:
$lastRec=count($results);
print_r($results[$lastRec]);

annoying array tags.. want a pretty output

What i'm trying to do is make my output usable for a spreadsheet.
I want each item in the output without array tags or not mashed together but starting with an asterisk and ending with a % sign.
<?php
$file = file_get_contents('aaa.txt'); //get file to string
$row_array = explode("\n",$file); //cut string to rows by new line
$row_array = array_count_values(array_filter($row_array));
foreach ($row_array as $key=>$counts) {
if ($counts==1)
$no_duplicates[] = $key;
}
//do what You want
echo '<pre>';
print_r($no_duplicates);
//write to file. If file don't exist. Create it
file_put_contents('no_duplicates.txt',$no_duplicates);
?>
Maybe this would give you what you want:
$str = "*" . implode("% *", $no_duplicates) . "%";
echo '<pre>';
echo $str;
echo '</pre>';

PHP explode multidimensional array

I am using file_get_contents() to import a text file.
In the text file, the format goes as below (example):
3434,83,8732722
834,93,4983293
9438,43933,34983
and so forth... basically it follows the pattern: integer, comma to split it, second integer, another comma to split it, third integer, then a new line begins. I need to get this into a table with the format following accordingly. So in other words, I would have a 3 column table and each new line in the text file would be a new row in the table.
This must be transcoded into a simple html table with <table> <tr> and <td>
I have never worked with multidimensional arrays and splitting text with that. This is why I'm seeking assistance. I really appreciate it! :)
You can do following :
$filename = 'abc.txt';
$content = file_get_contents($filename);
$explodedByBr = explode('<br/>', $content);
$table = "<table border='1'>";
foreach ($explodedByBr as $brExplode) {
$explodedByComma = explode(',', $brExplode);
$table .= "<tr>";
foreach ($explodedByComma as $commaExploded) {
$table .= "<td>" .$commaExploded. "</td>";
}
$table .= "<tr/>";
}
$table .= "</table>";
echo $table;
abc.txt has data in following format :
3434,83,8732722
834,93,4983293
9438,43933,34983
<?php
$file = 'path/to/file.txt';
echo '<table>';
while(!feof($file)) {
$line = fgets($file);
echo '<tr><td>' . implode('</td><td>',explode(',',$line)) . '</td></tr>';
}
echo '</table>';
?>
Try this:
Read the file into an array and then column'ize it by processing each line of the array by passing it through array_walk.
<?php
function addElements( &$v, $k ) {
$v1 = explode( ',', $v ); // break it into array
$v2 = '';
foreach( $v1 as $element ) {
$v2 .= '<td>'.$element.'</td>';
// convert each comma separated value into a column
}
$v = '<tr>'.$v2.'</tr>'; // add these columns to a row and return
}
// read the whole file into an array using php's file method.
$file = file( '1.txt' );
// now parse each line of the array so that we convert each line into 3 columns.
// For this, i use array_walk function which calls a function, addElements,
// in this case to process each element in the array.
array_walk( $file, 'addElements' );
?>
<html>
<head></head>
<body>
<table border="0">
<?php echo implode('',$file);?>
</table>
</body>
</html>
Hope it helps. See the php doc for file and array_walk. These are simple and convenient functions.

Categories