How to extract specific text from a text file in php? - php

i am having difficulties with extracting specific text from a text file. I have tried many different ways like using fopen or file to open the file but this wont allow me to use any of the string functions. So i have decided to use file_get_contents and extract the text i want with the string methods as follows:
<?php
$data = [];
$file =
file_get_contents("data.txt", 0, NULL, 148);
list($id, $data_names) = preg_split('[:]', $file);
array_push($names, $data_names);
echo $emails[0];
?>
I used preg_split to split the text i want at a specific character (:) and i put the data in an array. Which worked for the first line but i don't know how to go about doing it for the rest of the lines, i've tried a while loop but that just ends up in an infinite loop.
data.txt formatted like this:
1:hannah.Smith
2:Bob.jones
3:harry.white
....
Any suggestions on how to do this or a better approach would be greatly appreciated.

There is a function for that. This isn't CSV but change the delimiter. To just get the names:
$handle = fopen("data.txt", "r"));
while(($line = fgetcsv($handle, 0, ":")) !== FALSE) {
$names[] = $line[1];
}
To index the names by the ids:
while(($line = fgetcsv($handle, 0, ":")) !== FALSE) {
$names[$line[0]] = $line[1];
}
To get the ids and names in a multidimensional array, use:
while(($names[] = fgetcsv($handle, 0, ":")) !== FALSE) {}

Well you are not assigning the return value of file_get_contents to a variable. So the contents of the file are not being used.
You can use the file function. It reads the contents of a file to an array. Each element of the array is a line in the file. You can then loop over the array and parse each line. For example:
$names = array();
$file = file_get_contents("data.txt");
for ($count = 0; $count < count($file); $count++) {
list($id, $name) = $file[$count];
$names[] = $name;
}
/** print the contents of the names array */
print_R($names);

Related

how to create array inside array from text file in php

first, i have a text file
Samsung|us|new
iPhone|china|new
i want to convert the text file, and the result must be like this
[
[
'Samsung', 'us', 'new'
],
[
'iPhone', 'china', 'new'
]
]
i have already try this, but the code only return one array
code:
<?php
$a = file_get_contents("text.txt");
$b = explode('|', $a);
result:
[
'Samsung','us','new','iPhone','china','new'
];
According to the hint from Jeto I would do the following:
at first read the file with function file() with the flag FILE_IGNORE_NEW_LINES. This reads the file line by line and creates an array.
next step would be to iterate over each element and split by | character with explode().
This could be the resulting code:
$file = file('test.txt', FILE_IGNORE_NEW_LINES);
for($i = 0; $i < count($file); $i++)
{
$file[$i] = explode('|', $file[$i]);
}
This is because file_get_contents() reads the whole file including the line breaks.
You have to first explode() on \n. After that explode() on |.
Or with array_map() in one line:
$a = file_get_contents("text.txt");
$b = array_map(fn($line) => explode('|', $line), explode("\n", $a));
// $a with \n
// this explode splits the lines
// this explodes at the | character
Example: https://3v4l.org/24qla
If you want to read some big files you can use something like this:
function getCsvData($file, $delimiter = '|') {
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
yield $data;
}
fclose($handle);
}
}
foreach(getCsvData('test.txt') as $row) {
print_r($row);
}
Don't use file_get_contents open the file and read the file line by line. Then split the line.
https://www.php.net/manual/en/function.fgets.php
Here are some example to do this. You can use fgets for this. With file_get_contents you get the whole file.
Another solution is to explode by \r\n or \n the characters for new line. Then you have the single lines and you can split them by your delimiter. But in this case you write the whole content in an array what can cause some memory problem.
explode("\n",$homepage)

Convert a CSV file to force encapsilation

My ideal fix would be a function that can take a CSV file that does not have forced encapsulation (no quotes around values if the value has no spaces or is just a number) and convert it into a CSV file that makes sure every field is encapsulated with double quotes.
<?php
$raw_file = BASE_DIR."pathto/csv.csv";
$fixed_file = BASE_DIR."pathto/fixed.csv";
convert_file($raw_file, $fixed_file);
//move on with life!!
?>
Thanks for you help!
Use fgetcsv to get the contents of your original csv file and fputcsv (using the fourth parameter) to build the encapsulated file.
For example, supposing your column separator is ; :
<?php
$raw_file = BASE_DIR."pathto/csv.csv";
$fixed_file = BASE_DIR."pathto/fixed.csv";
// Getting contents
$raw_handle = fopen($raw_file, 'r');
$contents = array();
while (($data = fgetcsv($raw_handle, 0, ';')) !== false) {
$contents[] = $data;
}
fclose($raw_handle);
// Putting contents
$fixed_handle = fopen($fixed_file, 'w');
foreach ($contents as $line) {
fputcsv($fixed_handle, $line, ';', '"');
}
fclose($fixed_handle);
//move on with life!!
?>

fgetcsv skip blank lines in file

I have this script that I did, it basically grabs all the files in my "logs" folder and merge them all in one array file, my only problem is that, sometimes the script breaks if there is blank line or empty line! how can I tell it to automatically skip blank empty lines and go to next? blank lines are not necessarily at the top or bottom! could be in the middle of the csv file
<?php
$csv = array();
$files = glob('../logs/*.*');
$out = fopen("newfile.txt", "w");
foreach($files as $file){
$in = fopen($file, "r");
while (($result = fgetcsv($in)) !== false)
{
$csv[] = $result;
}
fclose($in);
fclose($out);
}
print json_encode(array('aaData' => $csv ));
?>
As you can read in the documentation for fgetcsv():
A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.
Checking for that before adding it to your data array should be sufficient:
while (($result = fgetcsv($in)) !== false) {
if (array(null) !== $result) { // ignore blank lines
$csv[] = $result;
}
}
This works 100% tested, simplest way. The explanation is that blank lines make fgetcsv return a non-empty array with just a null element inside.
if ($result[0] == NULL)
continue;
In short
$csv = array_map('str_getcsv', file($file_path, FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES));
Explanation
file reads the content of the file into an array. The FILE_SKIP_EMPTY_LINES will skip the empty lines in the file.
array_map will apply the function str_getcsv on each element of the array. str_getcsv will parse the string input for fields in
csv format and return an array containing the fields.
Read more about str_getcsv
Read more about file
Read more about array_map

Read .csv file and save its values in a list of arrays

I am new at php programming but I have been stuck with this code for some time.
I would like to read a .csv file line by line and then save its values in a list of arrays.
$file = fopen('Sub-Companies.csv', 'r');
while (($line =
fgetcsv($file)) !== FALSE) {
print_r($line);
list($customer_id[],$company_name[],$department[],$employee[],$country[],$zipcode[],$address[],$city[],
$smth1[], $smth2[], $phone_no1[],$phone_no2[],$email[],$website[],
$customer_no[],$problem1[],$problem2[]) = explode(";",$line); }
fclose($file); var_dump($customer_id);
The problem is that, although it is read correctly the file, then the explode is not working and the arrays appear to be null.
One thing that I am considering is that some arrays have more ";" than others, so that might be a problem, that is why I have the arrays $problem1 and $problem2, in order to store the values of this arrays.
Any help would be great!
You're using fgetcsv() in the wrong way.
We've come to this solution while chatting here on StackOverflow.
<?php
// Create file data.csv with your data
$handle = fopen('Sub-Companies.csv', 'r');
$customer_id = array();
$xyz_array = array();
// ...
// Better use a specified length (second parameter) instead of 0
// It slows down the whole process of reading the data!
while (($line = fgetcsv($handle, 0, ';')) !== FALSE) {
$customer_id[] = $line[0];
$xyz_array[] = $line[1];
}

Parse CSV file of links to php array, feed these links to simplehtmldom

I have a php code that will read and parse csv files into a multiline array, what i need to do next is to take this array and let simplehtmldom fire off a crawler to return some company stocks info.
The php code for the CSV parser is
$arrCSV = array();
// Opening up the CSV file
if (($handle = fopen("NASDAQ.csv", "r")) !==FALSE) {
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row $data is the variable for each line of the array
$c = count($data);
//Populate the array
for ($x=0;$x<$c;$x++) {
$arrCSV[$key][$x] = $data[$x];
}
$key++;
} // end while
// Close the CSV file
fclose($handle);
} // end if
echo "<pre>";
echo print_r($arrCSV);
echo "</pre>";
This works great and parses the array line by line, $data being the variable for each line. What i need to do now is to get this to be read via simplehtmldom, which is where it breaks down, im looking at using this code or something very similar, im pretty inexperienced at this but guess i would be needing a foreach statement somewhere along the line.
This is the simplehtmldom code
$html = file_get_html($data);
$html->find('div[class="detailsDataContainerLt"]');
$tickerdetails = ("$es[0]");
$FileHandle2 = fopen($data, 'w') or die("can't open file");
fwrite($FileHandle2, $tickerdetails);
fclose($FileHandle2);
fclose($handle);
So my qyestion is how can i get them both working together, i jave checked out simplehtmldom manual page several times and find it a littlebit vague in this area, the simplehtmldom code above is what i use in another function but by direclty linking so i know that it works.
regards
Martin
Your loop could be reduced to (yes, it's the same):
while ($data = fgetcsv($handle, 0, ',')) {
$arrCSV[] = $data;
}
Using SimpleXML instead of SimpleDom (Since it's standard PHP):
foreach ($arrCSV as $row) {
$xml = simplexml_load_file($row[0]); // Change 0 to the index of the url
$result = $xml->xpath('//div[contains(concat(" ", #class, " "), " detailsDataContainerLt")]');
if ($result->length > 0) {
$file = fopen($row[1], '2'); // Change 1 to the filename you want to write to
if ($file) {
fwrite($file, (string) $result->item(0));
fclose($file);
}
}
}
that should do it if I understood correctly...

Categories