It gives me this error Notice: Undefined variable: newfile and of course it also gives me fwrite() expects parameter 1 to be resource, null given cause of the first error. What I doing wrong?
$file = fopen("mycsv.csv", 'r');
$newfile = fopen("myjson.txt", 'w');
function write($text, $tab) {
$tabs = "";
for ($index = 0; $index < $tab; $index++) {
$tabs .= "\t";
}
fwrite($newfile, $text."
".$tabs); //error here
}
Have a read about variable scope in the manual
$file and $newfile are global, therfore $newfile cannot be accessed locally in your function. Either move it into the function, pass it in as a parameter or as a last resort declare it as global in the function
You need to make $newfile
global to be able to use it inside a function's scope:
function write($text, $tab) {
global $newfile;
// ... the rest
}
Any variable used inside a function is by default limited to the local function scope.
See: http://php.net/manual/en/language.variables.scope.php
You can do what you want if you make $newfile a global variable or pass it in as another function argument.
Function is out of scope. You could send the opened document direct to the function, that would allow it to be used within scope of the function.
function write($newfile,$text,$tab){
//the rest of your code
}
$returned = write($newfile,$text,$tab);