I was doing tests with a code that uses PHP's fopen
function to handle a file and fwrite
to write within the open file.
This is the code. It is about writing a set of results from the database in the file:
$arrDatos = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($arrDatos)
{
$archivo = 'text/archivo.txt';
$handler = fopen($archivo,'w');
/*Verificamos que el recurso se abrió*/
if($handler)
{
//var_dump($handler);
/*Encabezados*/
fwrite($handler,str_pad('ID',5));
fwrite($handler,str_pad('NOMBRE',15));
fwrite($handler,str_pad('APELLIDO',15));
fwrite($handler,PHP_EOL);
/*Contenido*/
foreach ($arrDatos as $row)
{
$intId=$row["actor_id"];
$strNombre=$row["actor_nombre"];
$strApellido=$row["actor_apellido"];
fwrite($handler,str_pad($intId,5));
fwrite($handler,str_pad($strNombre,15));
fwrite($handler,str_pad($strApellido,15));
fwrite($handler,PHP_EOL);
}
fclose($handler);
$txtContent = file_get_contents($archivo);
$txtHTML = htmlentities($txtContent);
}
else
{
$txtHTML='No se pudo abrir el archivo';
}
}
else
{
$txtHTML="La consulta no arrojó datos";
}
Reviewing the PHP Manual, it says that both fopen
as fwrite
return FALSE
when a problem occurs. But I would like to inform in my code of the specific problem that is happening: for example, if the user does not have read or write permissions in the folder where the resource is located, or any other error. That is why I would like to know if there is a way to get specific errors when using fopen
or fwrite
.