Reputation: 41
I have file with datas. Every line has name of author/authors..it looks like this:
"Giacometti, Jasminka"; "Mazor Jolic, Slavica"; "Josic, Djuro";
"Hoffmeister, Karin M"; "Grozovsky, Renata"; "Jurak Begonja, Antonija"; "Hartwig, John H";
"Jakopovic, Boris"; "Kraljevic Pavelic, Sandra"; "BelScak-Cvitanovic, Ana"; "Harej, Anja"; "Jakopovich, Ivan";
For example, for the first row:
"Giacometti, Jasminka"; "Mazor Jolic, Slavica"; "Josic, Djuro";
I need to get this and write it in another file:
"Giacometti, Jasminka"; "Mazor Jolic, Slavica";1
"Giacometti, Jasminka"; "Josic, Djuro";1
"Mazor Jolic, Slavica"; "Josic, Djuro";1
How can I do it in php? I tried with getting every line in the array, but then I don't know how to split datas from that row.
$handle = @fopen("datas.txt", "r");
$listA = array();
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$listA[] = $buffer;
}
Thank you.
Upvotes: 3
Views: 86
Reputation: 2376
I'm not sure exactly what you want to do with the authors, but this will separate each line into an array of authors;
<?php
$source_string = file_get_contents('source.txt'); // Load the source file.
$source_array = explode(PHP_EOL, $source_string); // Create an array of one element per line.
// Iterate over the source array.
foreach($source_array as $line) {
$trimmed = rtrim($line, ';'); // Trim the semicolon from the end of the line.
$array_of_authors = explode('; ', $trimmed); // Explode the line into an array of one element per author.
$output = print_r($array_of_authors, true);
echo "<div>Line: {$line}</div>";
echo "<xmp>{$output}</xmp>";
}
?>
The output produced by the above starts like this;
Line: "Giacometti, Jasminka"; "Mazor Jolic, Slavica"; "Josic, Djuro";
Array
(
[0] => "Giacometti, Jasminka"
[1] => "Mazor Jolic, Slavica"
[2] => "Josic, Djuro"
)
Upvotes: 0
Reputation: 1416
foreach ( $$listA as $key)
{
$part = explode(";",$key);
}
Split the string by using ;
as separater. You have to discard the last element of the $part
array as it will be ''
.
Here you have only three elements in array. So you don't require loops for permute. If you have more numbers, use permutations by loop.
Upvotes: 0
Reputation: 2807
First read the content content from the file that contains the data as full one complete string and then explode that string with end of line character, so each array element will now contain a row of data:
$data = file_get_contents("data.txt"); //data.txt is the file that contains rows of data
$authArr = explode(PHP_EOL, $data ); //this array contains all the rows in it
You can now use this $authArr
to write to another file by appending an new line character to the each row i.e each element of array that you will write to the file.
Upvotes: 3