Funk Forty Niner
Funk Forty Niner

Reputation: 74217

How to split content into equal parts then write to file in PHP

I have been reading/testing examples since last night, but the cows never came home.

I have a file with (for example) approx. 1000 characters in one line and want to split it into 10 equal parts then write back to the file.

Goal:

1. Open the file in question and read its content
2. Count up to 100 characters for example, then put a line break
3. Count 100 again and another line break, and so on till it's done.
4. Write/overwrite the file with the new split content

For example:

I want to turn this => KNMT2zSOMs4j4vXsBlb7uCjrGxgXpr

Into this:

KNMT2zSOMs
4j4vXsBlb7
uCjrGxgXpr

This is what I have so far:

<?php
$MyString = fopen('file.txt', "r");

$MyNewString;
$n = 100; // How many you want before seperation
$MyNewString = substr($MyString,0,$n); 
$i = $n;
while ($i < strlen($MyString)) {
$MyNewString .= "\n"; // Seperator Character
$MyNewString .= substr($MyString,$i,$n);
$i = $i + $n;
}
file_put_contents($MyString, $MyNewString);

fclose($MyString);
?>

But that is not working quite the way I anticipated.

I realize that there are other similiar questions like mine, but they were not showing how to read a file, then write back to it.

Upvotes: 1

Views: 653

Answers (3)

user849137
user849137

Reputation:

Hold on here. You're not giving a file name/path to file_put_contents();, you're giving a file handle.

Try this:

file_put_contents("newFileWithText.txt", $MyNewString);

You see, when doing $var=fopen();, you're giving $var a value of a handle, which is not meant to be used with file_put_contents(); as it doesnt ask for a handle, but a filename instead. So, it should be: file_put_contents("myfilenamehere.txt", "the data i want in my file here...");

Simple.

Upvotes: 1

Steve
Steve

Reputation: 3046

<?php

$str = "aonoeincoieacaonoeincoieacaonoeincoieacaonoeincoieacaonoeincoieacaon";

$pieces = 10;

$ch = chunk_split($str, $pieces);
$piece = explode("\n", $ch);
foreach($piece as $line) {
// write to file
}

?>

http://php.net/manual/en/function.chunk-split.php

Upvotes: 3

Jeff Lambert
Jeff Lambert

Reputation: 24661

Take a look at the documentation for str_split. It will take a string and split it into chunks based on length, storing each chunk at a separate index in an array that it returns. You can then iterate over the array adding a line break after each index.

Upvotes: 1

Related Questions