I've been given a list of data and I need to split it and move it into different text files. I've tried a few things so far but cant seem to get it to work.
<?php
/*
*order the file based on surname (col 2)
*create two new text files - class A and B
*split the source text into two equal lists
*format them: ID, firstname, lastname. all words must be first letter caps
*move each list to a new file.
*close files
*/
//This function converts every attribute/variable passed to it into a sentence case
function Uppercase($convert) {
return ucwords($convert);
}
//This function compares two items to see which one is higher
//src: http://php.net/manual/en/function.usort.php
function cmp($a, $b) {
$compResult = strcmp($a[1], $b[1]);
if ($compResult == 0) {
return strcmp($a[2], $b[2]);
}else {
return $compResult;
}
}
//This function gets rid of the whitespace that is not needed
function cut($c) {
return trim($c, " \n\r\0");
}
//open file
$myfile = fopen("students.csv", "r");
echo "A";
//initialise the array, giving them 'headers'
$array = array();
echo "B";
//sort through the data, moving it to a multidimentional array and setting the first letter in each item to uppercase
$i=0;
while(!feof($myfile)){
$line = fgets($myfile);
$pieces = explode(",", $line);
$array[$i][0] = $pieces[0];
$array[$i][1] = cut(Uppercase($pieces[2]));
$array[$i][2] = cut(Uppercase($pieces[1]));
$i++;
}
echo "C";
//sort the file by the second item in the array
usort($array, "cmp");
echo array_shift($array)."<br>";
echo "D";
//create class files
$fileA = fopen("Class 1.txt", "w");
$fileB = fopen("Class 2.txt", "w");
echo "E";
//get size of array
$arraylength = count($array);
//half the array length(
$half = ceil($arraylength /= 2);
//echo $half;
//echo $arraylength."</br>";
echo "F";
echo "<pre>";
print_r($array);
echo "</br>";
//move the first class into a text file
$k = 0;
foreach ($array as $key){
echo $key[0];
if ($k < $half) {
$current = file_get_contents($fileA);
$current .= $key;
}
}
echo "G";
fclose($fileA);
fclose($fileB);
fclose($myfile);
echo "H";
When this runs, I get the following line recurring for each item in the array
Warning: file_get_contents() expects parameter 1 to be a valid path, resource given in C:\xampp\htdocs\PHPLabs\EE1600Assignment.php on line 93
The document itself has 25 items that look like this:
123, billy, bobs
Any help is appreciated. Thank you
file_get_contents expects a file path, but you are providing a file handler. You probably want instead fgets($fileA).
Alternatively, if you want to read the complete file (it's not entirely clear from your code), you can use fread($fileA).
According to the documentation, file_get_contents requires a path to the file you want to open (as per the error message you're getting - file_get_contents() expects parameter 1 to be a valid path).
You're passing in $fileA - which you created earlier using an fopen call
fopen("Class 1.txt", "w");
Related
We have made an array from a text file full of numbers separated by commas, each new line is a new part of the array. (we are not allowed to use explode for this)
We are trying to create a transpose_matrix function to 'transpose' the array now.
Using tutorials on the internet, this is what we have come up with so far, but it doesn't work :(
$myfile = fopen("text1.txt", "r") or die("Unable to open file!");
//echo fread($myfile,filesize("text1.txt"));
$file1 = file("text1.txt");
$store1 = array();
for ($a = 0; $a<count($file1); $a++)
{
array_push($store1, $file1[$a]);
}
for ($k = 0; $k<count($store1); $k++)
{
echo "Line $store1[$k] <br/> END <br/>";
}
function transpose($store1) {
$file1 = file("text1.txt");
$store1 = array();
if (count($store1) == 0) // special case: empty matrix
return array();
else if (count($store1) == 1) // special case: row matrix
return array_chunk($store1[0], 1);
function myCallbackMethod() {
var_dump ($store1);
}
array_unshift($store1, NULL); // the original matrix is not modified because it was passed by value
return call_user_func_array('myCallbackMethod',$store1);
}
transpose($store1);
fclose($myfile);
}
Try reading with fscanf().
something like
fscanf($file_link, '%s\n', $temp);
array_push($array, $temp);
should work.
Sukhdev Mohan
I have been researching fgetcsv() and have the following working code:
$file = fopen($pathToCsv,"r");
$data = array();
while(! feof($file))
{
array_push($data, fgetcsv($file));
}
fclose($file);
However, when I try to adapt this to dynamically accept an unknown number of csv files stored into an array, things cease to work:
$year = $_POST['year'];
$m = "maths".$year;
$sheets = $$m; //an array containing between 5 an 8 paths to csv and other info
$data = array();
function ArrayFromCsv($file, $i) {
while(! feof($file))
{
array_push($data[$i], fgetcsv($file)); //line 15
}
fclose($file);
}
for ($i = 0; $i < count($$m); $i++){
array_push($data, array());
$x = fopen($sheets[$i]['csv'],'r');
ArrayFromCsv($x, $i);
}
I get: Warning: array_push() expects parameter 1 to be array, null given in ... on line 15
I'm not how to research this further. Is there a better way or obvious mistake? I've tried a number of methods.
You dont have access to the global $data variable inside of the function ArrayFromCsv. You either need to use "global $data" inside the function, which is bad, so DON'T
Or you could create a temporary array inside the function, which you return when the function ends and put the returned value from the function into $data[$i]. Also you should not open a file outside of a function and close it inside of a function. That could lead to undefined behaviour someday when your code gets bigger.
function ArrayFromCsv($file, $i) use (&$data) {
while(! feof($file))
{
array_push($data[$i], fgetcsv($file)); //line 15
}
fclose($file);
}
i have 2 files:
text1.txt and text2.txt
how can i do this: if found a row in text1.txt that match to a row from text2.txt, delete it (or display the unique)?
this is what i have so far:
$a = file('text1.txt');
$b = file('text2.txt');
$contents = '';
foreach($b as $line2) {
foreach($a as $line1) {
if(!strstr($line1, $line2)) {
$contents .= $line1;
}
}
}
file_put_contents('unique.txt', $contents);
That will be:
file_put_contents('unique.txt', array_diff(file('text1.txt'), file('text2.txt')));
-since you're loading your files into RAM entirely, I suppose it's acceptable solution.
Also you may want to define your own function to determine if strings are equal. Logic then will be the same, but array_udiff() should be used
Hello, how to read txt file using php and replacement with array?
i want read file like this:
||Search||,||s||---||Images||,||i||
this my php code:
$f = fopen("test.txt", "r");
$image= "Imgaes";
// Read line by line until end of file
while (!feof($f)) {
// Make an array using comma as delimiter
// $arrM = explode("---",fgets($f));
$arr = explode("||---||",fgets($f));
// Write links (get the data in the array)
$num = 1;
while($num <= 30) {
list($eng,$fa) = explode("||,||", $arr[$num]);
foreach($html->find('html') as $full) {
$all = $full->innertext;
}
$fe = str_replace($eng,$fa,$all);
$num = $num+1;
}
echo $fe;
}
fclose($f);
but this not work:(!!!
before the explode, parse your data in this function:
// Function arrayData
function arrayData($data){
# code...
// Create an array out of each line
$data_array=explode("\n", $data);
// Find the last key in the array
$last_key=count($data_array)-1;
// If the last line is empty revise the last key downwards until there's actually something there
while(empty($data_array[$last_key]))
{
$last_key-=1;
}
// Figure out the first key based upon the value set for the number of lines to display
$first_key=$last_key-($this->num_lines-1);
// Start a new array to store the last X lines in
$final_array=array();
// Work through the array and only add the last X lines to it.
foreach($data_array as $key => $value)
{
if($key >= $first_key && $key <= $last_key)
{
$final_array[]=$value;
}
}
return $final_array;
} // end function
I have a file here which contains list of database names and its corresponding size.
Now I want to sort the size from the largest to the lowest, and the database name
should go along it upon display.Am using PHP here..
Can anyone help me out?
Here's a simple code for that:
$file_name = test.txt
$handle = #fopen($file_name, "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
$data = explode(" ",$buffer);
echo $data[1]."\n";
}
fclose($handle);
}
File looks like this:
DatabaseName 300 KB
Note: $data[1] contains the sizes. Should i place it on an array? how about the db name?
Answers are very much appreciated. =)
First you need to build an array with an element you can actually sort on, then use usort or similar to perform the sort based on your custom criteria.
//first build up an array of databases with a unified size in bytes, ensuring
//we account for those postfixes like KB,MB,and GB
$databases=array();
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
$data = explode(" ",$buffer);
if (count($data)==3)
{
$size=$data[1];
switch ($data[2])
{
case 'KB': $size*=1024; break;
case 'MB': $size*=1024*1024; break;
case 'GB': $size*=1024*1024*1024; break;
}
$data[3]=$size;
$databases[]=$data;
}
else
{
die("Bad line in file: $buffer");
}
}
Now sort with a custom comparison function to sort from high to low based on that calculated size:
function cmp($a, $b)
{
if ($a[3] == $b[3]) {
return 0;
}
return ($a[3] < $b[3]) ? 1 : -1;
}
usort($databases, "cmp");
You can use the file() PHP function here.
Your text file is like :
DatabaseName 300 KB
DatabaseName 300 KB
DatabaseName 300 KB
DatabaseName 300 KB
I think you can use the PHP native function on arrays.
$data = file('myfile.txt');
foreach($data as $one_line)
{
$db[] = explode(" ",$one_line)
//will have $db[0][0] = 'dbname';
//will have $db[0][2] = '30';
//will have $db[0][2] = 'KB';
//will have $db[1][0] = 'dbname';
//will have $db[1][3] = '30';
//will have $db[1][2] = 'KB';
}
array_multisort($db[1], SORT_NUMERIC, SORT_DESC);
See this comment in documentation, the same structure : http://fr2.php.net/manual/en/function.array-multisort.php#79491
Or maybe you have to flip the array, so you can have size in index and name in value.
function databases_sort($a, $b) {
if ($a[1] == $b[1]) { return 0; }
return ($a[1] < $b[1]) ? -1 : 1;
}
$file_name = "test.txt";
$handle = #fopen($file_name, "r");
$databases = array();
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
$data = explode(" ",$buffer);
$databases[] = $data;
//echo $data[1]."\n";
}
usort($databases, "databases_sort");
foreach ($databases as $d) {
echo $d[1];
}
fclose($handle);
}
This code stores your information in an array, then runs a custom sorting function on your array, sorting it by the value of element 1 in the array. Higher values (larger database sizes) get sorted to the top of the list.
Warning: I haven't actually tested this code, but you can see the usort documentation if there are any bugs that need fixing.
Edit: d'oh, beaten by a few seconds :-)
Have you thought about parsing into a binary search tree structure instead of an array? That way you could have the data sorted with a tree traversal and you could have fast lookup too.