Pregunta

Quiero obtener el contenido de un archivo .php en una variable en otra página.

tengo dos archivos, myfile1.php y myfile2.php.

miarchivo2.php

<?PHP
    $myvar="prashant"; // 
    echo $myvar;
?>

Ahora quiero que myfile2.php repita el valor en una variable en myfile1.php. Lo intenté de la siguiente manera, pero también está tomando todo el contenido, incluida la etiqueta php ().

<?PHP
    $root_var .= file_get_contents($_SERVER['DOCUMENT_ROOT']."/myfile2.php", true);
?>

Dígame cómo puedo obtener el contenido devuelto por un archivo PHP en una variable definida en otro archivo PHP.

Gracias

¿Fue útil?

Solución

Puede utilizar el directiva include para hacer esto.

Archivo 2:

<?php
    $myvar="prashant";
?>

Archivo 1:

<?php 

include('myfile2.php');
echo $myvar;

?>

Otros consejos

Hay que diferenciar dos cosas:

  • ¿Quieres capturar la salida (echo, print,...) del archivo incluido y utilizar la salida en una variable (cadena)?
  • ¿Quieres devolver ciertos valores de los archivos incluidos y usarlos como una variable en tu anfitrión ¿guion?

Las variables locales en sus archivos incluidos siempre se moverán al alcance actual de su anfitrión guión: esto debe tenerse en cuenta.Puede combinar todas estas funciones en una:

include.php

$hello = "Hello";
echo "Hello World";
return "World";

host.php

ob_start();
$return = include 'include.php'; // (string)"World"
$output = ob_get_clean(); // (string)"Hello World"
// $hello has been moved to the current scope
echo $hello . ' ' . $return; // echos "Hello World"

El return-La característica es útil especialmente cuando se utilizan archivos de configuración.

config.php

return array(
    'host' => 'localhost',
     ....
);

app.php

$config = include 'config.php'; // $config is an array

EDITAR

Para responder a su pregunta sobre la penalización de rendimiento al usar los buffers de salida, hice algunas pruebas rápidas.1.000.000 iteraciones de ob_start() y el correspondiente $o = ob_get_clean() tarda unos 7,5 segundos en mi máquina con Windows (posiblemente no sea el mejor entorno para PHP).Yo diría que el impacto en el rendimiento debería considerarse bastante pequeño...

Si sólo quería el contenido echo() 'ed por la página incluida, se puede considerar el uso de búferes de salida:

ob_start();
include 'myfile2.php';
$echoed_content = ob_get_clean(); // gets content, discards buffer

http://php.net/ob_start

Siempre intento para evitar ob_ funciones. En su lugar, yo uso:

<?php
$file = file_get_contents('/path/to/file.php');
$content = eval("?>$file");
echo $content;
?>

"En realidad, solo estaba buscando si existe algún método de tipo de retorno que pueda darme directamente el valor". Acabas de responder tu propia pregunta.

Ver http://sg.php.net/manual/en/function.include.php, Ejemplo #5

archivo1.php:

<? return 'somevalue'; ?>

archivo2.php:

<?

$file1 = include 'file1.php';
echo $file1; // This outputs 'somevalue'.

?>

Puede utilizar buffers de salida, que almacenará todo lo que de salida, y no va a imprimirlo a menos que explícitamente se lo pida o no terminen / borrar las memorias intermedias para el final del camino de la ejecución.

// Create an output buffer which will take in everything written to 
// stdout(i.e. everything you `echo`ed or `print`ed)
ob_start()
// Go to the file
require_once 'file.php';
// Get what was in the file
$output = ob_get_clean();

Si desea obtener todo el uso del sitio por

<?php
$URL = 'http://www.example.com/';
$homepage = file_get_contents($URL);
echo $homepage;
?>

Por favor, intente este código

myfile1.php

<?php
    echo file_get_contents("http://domainname/myfile2.php");
?>

myfile2.php

<?PHP
    $myvar="prashant";
    echo $myvar;
?>

Si desea devolver la salida de código en un archivo, simplemente hacer una llamada a la API REST a ella. De esta manera, se puede utilizar el mismo archivo de código para las llamadas ajax, API REST, o para su código interno de PHP.

Se requiere cURL para ser instalado, pero no hay buffers de salida o ninguna incluye, sólo la página ejecutado y regresó en una cadena.

Te daré el código que he escrito. Funciona con casi todos los servidores RESTO / web (e incluso trabaja con Equifax):

$return = PostRestApi($url);

o

$post = array('name' => 'Bob', 'id' => '12345');
$return = PostRestApi($url, $post, false, 6, false);

Aquí es la función:

/**
 * Calls a REST API and returns the result
 *
 * $loginRequest = json_encode(array("Code" => "somecode", "SecretKey" => "somekey"));
 * $result = CallRestApi("https://server.com/api/login", $loginRequest);
 *
 * @param string $url The URL for the request
 * @param array/string $data Input data to send to server; If array, use key/value pairs and if string use urlencode() for text values)
 * @param array $header_array Simple array of strings (i.e. array('Content-Type: application/json');
 * @param int $ssl_type Set preferred TLS/SSL version; Default is TLSv1.2
 * @param boolean $verify_ssl Whether to verify the SSL certificate or not
 * @param boolean $timeout_seconds Timeout in seconds; if zero then never time out
 * @return string Returned results
 */
function PostRestApi($url, $data = false, $header_array = false,
    $ssl_type = 6, $verify_ssl = true, $timeout_seconds = false) {

    // If cURL is not installed...
    if (! function_exists('curl_init')) {

        // Log and show the error
        $error = 'Function ' . __FUNCTION__ . ' Error: cURL is not installed.';
        error_log($error, 0);
        die($error);

    } else {

        // Initialize the cURL session
        $curl = curl_init($url);

        // Set the POST data
        $send = '';
        if ($data !== false) {
            if (is_array($data)) {
                $send = http_build_query($data);
            } else {
                $send = $data;
            }
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($curl, CURLOPT_POSTFIELDS, $send);
        }

        // Set the default header information
        $header = array('Content-Length: ' . strlen($send));
        if (is_array($header_array) && count($header_array) > 0) {
            $header = array_merge($header, $header_array);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

        // Set preferred TLS/SSL version
        curl_setopt($curl, CURLOPT_SSLVERSION, $ssl_type);

        // Verify the server's security certificate?
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, ($verify_ssl) ? 1 : 0);

        // Set the time out in seconds
        curl_setopt($curl, CURLOPT_TIMEOUT, ($timeout_seconds) ? $timeout_seconds : 0);

        // Should cURL return or print out the data? (true = return, false = print)
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        // Execute the request
        $result = curl_exec($curl);

        // Close cURL resource, and free up system resources
        curl_close($curl);
        unset($curl);

        // Return the results
        return $result;

    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top