Pergunta

Eu quero começar conteúdo de um arquivo .php em uma variável em outra página.

Eu tenho dois arquivos, myfile1.php e myfile2.php.

myfile2.php

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

Agora eu quero obter o valor ecoado pelo myfile2.php em uma variável em myfile1.php, eu tentei a maneira follwing, mas a sua tomar todo o conteúdo, incluindo tag php () também.

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

Por favor me diga como posso obter o conteúdo retornado por um arquivo PHP em uma variável definida em outro arquivo PHP.

Graças

Foi útil?

Solução

Você pode usar o incluem directiva para fazer isso.

Arquivo 2:

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

Arquivo 1:

<?php 

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

?>

Outras dicas

Você tem que diferenciar duas coisas:

  • Você quer capturar a saída (echo, print, ...) do arquivo incluído e usar a saída em uma variável (string)?
  • Você quer retornar certos valores a partir dos arquivos incluídos e usá-los como uma variável no seu hospedeiro script?

As variáveis ??locais em seus arquivos incluídos sempre será movido para o escopo atual de sua hospedeiro roteiro - isso deve ser observado. Você pode combinar todos esses recursos em um:

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"

A característica-return vem a calhar, especialmente quando utilizando arquivos de configuração.

config.php

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

app.php

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

Editar

Para responder à sua pergunta sobre a penalidade de desempenho ao usar os buffers de saída, eu apenas fiz alguns testes rápidos. 1.000.000 iterações de ob_start() ea correspondente $o = ob_get_clean() demorar cerca de 7,5 segundos na minha máquina Windows (possivelmente não o melhor ambiente para PHP). Eu diria que o impacto no desempenho deve ser considerado muito pequeno ...

Se você só queria o conteúdo echo()'ed pela página incluída, você poderia pensar em usar o buffer de saída:

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

Consulte http://php.net/ob_start

Eu sempre tento evitar ob_ funções. Em vez disso, eu uso:

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

"Na verdade eu estava apenas procurando que há algum método tipo de retorno que pode diretamente me dar o valor." - Você só respondeu à sua própria pergunta

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

file1.php:

<? return 'somevalue'; ?>

file2.php:

<?

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

?>

Você pode usar buffers de saída, que irá armazenar tudo o que de saída, e não imprimi-lo, a menos que você diga explicitamente que ele, ou não terminam / limpar os buffers até o final do caminho de execução.

// 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();

Se você quiser obter todos uso do site mais por

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

Por favor, tente este código

myfile1.php

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

myfile2.php

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

Se você quiser retornar a saída de código em um arquivo, basta apenas fazer uma chamada API RESTful a ele. Dessa forma, você pode usar o mesmo arquivo de código para chamadas ajax, REST API, ou para o seu código PHP interno.

Ela exige cURL para ser instalado, mas há buffers de saída ou não inclui, apenas a página executado e retornou em uma string.

Eu vou dar-lhe o código que eu escrevi. Ele funciona com quase todos os servidor REST / web (e ainda trabalha com Equifax):

$return = PostRestApi($url);

ou

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

Aqui é a função:

/**
 * 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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top