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
Related
This question already has answers here:
PHP: Remove duplicate elements and get the latest data in the array
(4 answers)
Closed 5 months ago.
Please a have some days trying to resolve a code To duduplicate csv file
the idea is to browse the csv file, remove duplicates and let the line that has the maximum id
For Example this file CSV FILE TO duduplicate
And the result will be rewriting of result into csv
while (($this->lineInWork = fgetcsv($handle, 0, $delimiter)) !== false) {
if ($index == 0) {
if (!$this->checkHeaderFile()) {
fclose($handle);
return false;
}
} else {
$idProject = $this->columns[self::ID_PROJET]['index'];
$TitleProject = $this->columns[self::Title_Project]['index'];
$currentTitle = null;
if ($this->lineInWork[$TitleProject] != $currentTitle)
{
$currentTitle = $this->lineInWork[$TitleProject];
array_push($this->temporary_file[$currentTitle], $this->lineInWork);
}
}
$index++;
}
fclose($handle);
The problem is not to rewrite file but is to build an array with the right lines
I would probably do two different sorts for this (assuming I have understood what you are requiring). I have created a quick csv writer, which you may already have:
protected function saveToCsv($data, $path)
{
$fp = fopen($path, 'w');
foreach ($data as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
}
Script to filter and sort:
# Create a storage array
$new = [];
# Increment array to determine header row
$i = 0;
# Turn the csv file to array
$array = array_map('str_getcsv', file('original.csv'));
# Sort low to high by the ID_project
usort($array, function($a, $b){
return ($a[0] < $b[0]);
});
# Loop the array and just re-assign over the top of each instance of value
# which will eventually assign the last value (highest)
foreach($array as $row) {
if($i == 0) {
# Save header to put back into the copy csv
$header = $row;
$i++;
continue;
}
# Assign by id so the values are unique and sortable after
if(!isset($new[$row[2]]))
$new[$row[2]] = $row;
}
# Resort by the app_id
ksort($new);
# Save the new CSV somewhere with the header merged
$this->saveToCsv(array_merge([$header], $new), 'copy.csv');
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'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");
I had a script called CSVimporter V3 for PHP that I used to run on a website and it worked fine. A couple of years later I've now dug out the same script to use on another project, all works okay except the CSV files are being read as one long line, as opposed to header row and multiple lines.
Here is part of the script.
Any ideas why it would be being read as a long line?
<?php
// Reference session variable for short-hand
$f = &$_SESSION['csv_file'];
// Open file - fp = file pointer
if (!$fp = #fopen($f, 'r')) {
error(L_ERROR_PREVIEW_NO_FILE);
} else {
// Array to store each row to be inserted
$batch = array();
// Row counter
$rc = 0;
// Work out starting row
switch ($_SESSION['csv_first_row']) {
case 'data':
$start_row = 0;
break;
default:
$start_row = 1;
}
// Get contents, while below preview limit and there's data to be read
while ($data = fgetcsv($fp, 1024, delimiter_to_char($_SESSION['csv_delimiter']))) {
if ($rc < $start_row) {
// Incremement counter
$rc++;
// Go to next loop
continue;
} else {
// Array to store data to be inputted
$values = array();
// Loop data
for ($i = 0; $i < count($data); $i++) {
// If data is wanted, put data into array
if (array_key_exists($i, $column_index)) {
$values[$column_index[$i]] = $data[$i];
}
}
// Sort array into correct order by index
ksort($values);
// Join values together and store in array
$batch[] = '("' . implode('", "', str_replace('"', '\"', $values)) . '","'.$accti.'","'.$impt.'")';
}
}
}
// Close the file
fclose($fp);
I added this at the top of the code and it all works now!
ini_set('auto_detect_line_endings', true);
I have a simple ini file:
[section_one]
test = abc
[section_two]
yada = blah
#and_so=on
I wrote a parser function to update it b/c my comment char is '#' instead of ';' -- so parse_ini_file() complains. But here's my quick & dirty solution:
<?php
function edit_ini_file ($fName, $fKey, $fVal) {
print"<h4>Search: $fKey = $fVal </h4>";
// declarations
$_comntChar='#';
$_headrChar='[';
$keyMatch=FALSE;
$iniArray = array(); // new array in memory
$dataOut = ''; // datastream for output file
// temp cursor vars for looping & reporting
$verbose = 1;
$curSec = ''; // current section
$curKey = ''; // current key
$curVal = ''; // current value
$curLine=-1; // current line Number
if (isset($fName)) {
if (!is_file($fName)) return FALSE;
$lines = file($fName);
//read file as array of lines
foreach ($lines as $line) {
$curLine+=1;
if ($verbose) print '<br/>['.$curLine.'][IN:] '.$line;
//parse for k/v pairs, comments & section headings
if ( (strpos($line,$_headrChar)==1) // assume heading
|| (strpos($line,$_comntChar)==1) // assume comment
|| (!strpos($line,'=')) // also skip invalid k/v pairs
){
array_push($iniArray, $lines[$curLine] ); //stuff the entire line into array.
if ($verbose) print " - no k/v";
} else { // assume valid k/v pair
//split k/v pairs & parse for match
$pair = explode('=', $line);
$curKey = trim($pair[0]);
$curVal = trim($pair[1]);
if ($verbose) print "[KV]: k=$curKey:v=$curVal";
if (trim($curKey) === trim($fkey)) { // <=== THE BUGGER: never returns true:
$keyMatch=TRUE;
print ("MATCH: Replacing value in for key=$curKey in Section $curSec at line $curLine<br/>");
array_push ($iniArray, array($curKey => $fVal ));
} else {
array_push ($iniArray, array($curKey => $curVal ));
} //end-matcher
} //end-parser
} //end foreach
if (!$keyMatch) { //append new data to end
print "<br/>Key not Found. Appending! <br/>";
array_push ($iniArray, array($fKey => $fVal) );
}
//reformat nested array as one long string for a single bulk-write to disk.
foreach($iniArray as $curSect => $val) {
if (is_array($val)) {
foreach($val as $curKey => $curVal)
$dataOut .= "$curKey = $curVal\n";
} else { $dataOut .= "$val"; }
}
print "dataout:<pre>" .$dataOut. "</pre>";
//put file & pass return val
return (file_put_contents($filename, $dataOut)) ? TRUE : FALSE;
}//if isset
}//end-func
Basically I'm just exploding a text file line-by-line stuffing a new array and dumping it back to the disk
MY BUG: for some reason my comparison trying strcmp() or "==" or "===" never seems to work...
if (trim($curKey) === trim($fkey)) { doSomething.. }
That little BUGGER is driving me nuts b/c I know it's gotta be something stupid.
ANy point in the right direction would be appreciated...
Is it $fKey or $fkey?
Make a decision!
;)