Append to a specific line in a text file

Asked

Viewed 82 times

0

Good morning, I have a function that makes an append in certain line of my xml file.

function addInFile($file, $lineNumber, $content)
{
    $fileTemp = "$file.bak";
    $currentLine = 0;

    $fpRead = fopen($file, 'r');
    $fpWrite = fopen($fileTemp, 'w');

    try {
        if ($fpRead) {
            while (($linha = fgets($fpRead)) !== false) {
                if ($currentLine == $lineNumber) {
                    $linha .= $content . PHP_EOL;
                }

                fwrite($fpWrite, $linha);
                $currentLine += 1;
            }
        }
    } catch (\Exception $err) {
        echo $err->getMessage() . PHP_EOL;
    } finally {
        fclose($fpRead);
        fclose($fpWrite);
        unlink($file);
        rename($fileTemp, $file);
    }
}

Only that I need to save my file outside the root of the project config/filesystem.php to receive a record I called public

'public' => [
            'driver' => 'local',
            'root' => storage_path('../../../public_html/xmls'),
            'visibility' => 'public',
        ],

My problem is I don’t know how to turn the fopen, fgets, fclose, unlink, rename, etc... with the Storage::disk() do laravel. In case anyone can help me, I’d like to thank you in advance.

  • There seems to be no specific function in Laravel to make an append on a specific line. The example you posted already seems to do this and usually that is enough. There is nothing to change. Perhaps, at most, a normalization, code reduction, optimization, etc. But there is not much to do because there is no equivalent described in the Laravel documentations. Maybe File::Get(), which returns the entire file and then make a explode() in line breaks. What would be the same as what you are doing, only in a more messed up way.

  • Since you are dealing with XML, you could consider using Simplexml, see: http://php.net/manual/simplexmlelement.addchild.php

  • In the fwrite() function I pass 2 arguments, the content and the line I want the append to be made. What I need to know is if Laravel’s Storage has a function that does this.

  • As I commented above, I found nothing in the documentation. https://laravel.com/docs/5.3/filesystem.

1 answer

0

I managed to solve.

php opens the files that are outside the root of Laravel, the only thing I needed to do was pass the complete path of the file.

In a function created in another class, it looks something like this:

public function test(){
      $url = Storage::disk('public')->getDriver()->getAdapter()->getPathPrefix();
      $fileManager->addInFile($url . $path, 7, $content);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.