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 aexplode()
in line breaks. What would be the same as what you are doing, only in a more messed up way.– Daniel Omine
Since you are dealing with XML, you could consider using Simplexml, see: http://php.net/manual/simplexmlelement.addchild.php
– Daniel Omine
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.
– Ivan Moreira
As I commented above, I found nothing in the documentation. https://laravel.com/docs/5.3/filesystem.
– Daniel Omine