file

(PHP 3, PHP 4 , PHP 5)

file -- Lee un archivo entero hacia una matriz

Descripción

array file ( string nombre_archivo [, int usar_ruta_inclusion [, resource contexto]])

Función idéntica a readfile(), excepto que file() devuelve el archivo en una matriz. Cada elemento de la matriz corresponde a una línea en el archivo, con el salto de línea aun incluido. Si ocurre un fallo, file() devuelve FALSE.

Es posible usar el parámetro opcional usar_ruta_inclusion, y definirlo como "1", si desea buscar por el archivo en include_path, también.

<?php
// Obtiene un archivo en una matriz. En este ejemplo usaremos HTTP
// para obtener el codigo fuente HTML de una URL.

$lineas = file('http://www.example.com/');

// Recorrer nuestra matriz, mostrar el codigo HTML como codigo fuente
// HTML, y los numeros de linea tambien.
foreach ($lineas as $linea_num => $linea) {
    echo
"L&iacute;nea #<b>{$linea_num}</b> : " . htmlspecialchars($linea) . "<br />\n";
}

// Otro ejemplo, obtengames una pagina web como una cadena. Vea
// tambien file_get_contents().
$html = implode('', file('http://www.example.com/'));
?>

Sugerencia: Puede usar una URL como nombre de archivo con esta función si los fopen wrappers han sido activados. Consulte fopen() para más detalles sobre cómo especificar el nombre de fichero y Apéndice L una lista de protocolos URL soportados

Nota: Cada línea en la matriz resultante incluye el final de línea, así que aun necesita usar rtrim() si no quiere conservar el final de línea.

Nota: Si sufre problemas con PHP no reconociendo los finales de línea cuando lee archivos creados en un Macintosh (o leyendo archivos sobre uno), puede probar activando la opción de configuración auto_detect_line_endings.

Nota: A partir de PHP 4.3.0, puede usar file_get_contents() para devolver el contenido de un archivo como una cadena.

En PHP 4.3.0 file(), se volvió una función segura con material binario.

Nota: Context support was added with PHP 5.0.0.

Aviso

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself.

Vea también readfile(), fopen(), fsockopen(), popen(), file_get_contents(), y include().