【问题标题】:How to execute and get content of a .php file in a variable?如何在变量中执行和获取 .php 文件的内容?
【发布时间】:2010-10-25 11:33:00
【问题描述】:

我想在其他页面的变量中获取 .php 文件的内容。

我有两个文件,myfile1.phpmyfile2.php

myfile2.php

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

现在我想在 myfile1.php 的一个变量中获取 myfile2.php 回显的值,我尝试了以下方式,但它也获取了包括 php tag() 在内的所有内容。

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

请告诉我如何将一个 PHP 文件返回的内容放入另一个 PHP 文件中定义的变量中。

谢谢

【问题讨论】:

  • 下面不接受的答案是更好的答案:stackoverflow.com/a/851773/632951
  • 一定要小心,因为如果你要使用 ob_get_contents() ,那么你可能需要做 ob_end_flush ,否则你可能会遇到问题,如果你使用将使用任何php header 之后的命令。

标签: php file return file-get-contents


【解决方案1】:

你必须区分两件事:

  • 是否要捕获包含文件的输出(echoprint、...)并在变量(字符串)中使用输出?
  • 是否要从包含的文件中返回某些值并将它们用作 host 脚本中的变量?

包含文件中的局部变量将始终移动到 host 脚本的当前范围 - 应注意这一点。您可以将所有这些功能合二为一:

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"

return-功能非常有用,尤其是在使用配置文件时。

config.php

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

app.php

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

编辑

为了回答您关于使用输出缓冲区时性能损失的问题,我只是做了一些快速测试。在我的 Windows 机器上,ob_start() 和相应的 $o = ob_get_clean() 的 1,000,000 次迭代大约需要 7.5 秒(可以说不是 PHP 的最佳环境)。我会说性能影响应该被认为是很小的......

【讨论】:

    【解决方案2】:

    如果您只想要包含页面的内容echo()',您可以考虑使用输出缓冲:

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

    http://php.net/ob_start

    【讨论】:

    • ob_start() 对我来说是新的。那么,@harto 你能建议我根据性能,你的方法还是@zombat 建议的方法,哪种方法会做得更好??
    • 输出缓冲对性能的影响很小,因为初始化和维护缓冲区会产生开销。
    • @Prashant:我没有任何可用数据,但我猜对性能的影响可以忽略不计。您可以尝试这两种方法,看看两者之间是否存在可测量的差异,但我认为确实非常小。
    【解决方案3】:

    我总是尽量避免使用 ob_ 函数。相反,我使用:

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

    【讨论】:

    • 你的回答很有趣。你能分享一下为什么你避免输出缓冲,而是使用 eval() 吗?您的回答对我来说将是一个很好的知识。
    • 感谢eval("?&gt;$file") 的技巧。这真的很有用。
    • OB_函数修改输出缓冲区,而CMS中的许多其他代码当时可能正在独立使用缓冲区函数,可能会发生冲突,或者清理缓冲区,或者修改它......所以,我从不碰它。
    • 如果 eval() 是答案,那么您几乎肯定会问错问题。 -- Rasmus Lerdorf,PHP 的 BDFL
    【解决方案4】:

    您可以使用include 指令来执行此操作。

    文件 2:

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

    文件 1:

    <?php 
    
    include('myfile2.php');
    echo $myvar;
    
    ?>
    

    【讨论】:

    • 我已经知道这个方法并且效果很好,但是除了这个没有别的办法了吗?
    • @Prashant 您对这种方法有什么问题?它是为了这样做而缩进的。
    • 其实我只是在看有没有“return”类型的方法可以直接给我价值。无论如何,我采用了@zombat 的回答,因为@harto 建议的方法可能存在一些性能问题,我不能在性能上妥协。谢谢你们。
    【解决方案5】:

    “其实我只是在看有没有可以直接给我价值的返回类型方法” - 你刚刚回答了你自己的问题。

    参见http://sg.php.net/manual/en/function.include.php,示例#5

    file1.php:

    <? return 'somevalue'; ?>
    

    file2.php:

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

    【讨论】:

    • 这值得更多观看!
    【解决方案6】:

    您可以使用输出缓冲区,它将存储您输出的所有内容,并且不会将其打印出来,除非您明确告诉它,或者在执行路径结束时不结束/清除缓冲区。

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

    【讨论】:

      【解决方案7】:

      如果你想得到整个网站的使用

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

      【讨论】:

        【解决方案8】:

        请试试这个代码

        myfile1.php

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

        myfile2.php

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

        【讨论】:

          【解决方案9】:

          如果您想从文件中的代码返回输出,只需对其进行 RESTful API 调用即可。这样,您可以将相同的代码文件用于 ajax 调用、REST API 或您的内部 PHP 代码。

          它需要安装 cURL 但没有输出缓冲区或没有包含,只是执行的页面并返回到一个字符串中。

          我会给你我写的代码。它适用于几乎所有 REST/Web 服务器(甚至适用于 Equifax):

          $return = PostRestApi($url);
          

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

          函数如下:

          /**
           * 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;
          
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-01-30
            • 1970-01-01
            • 1970-01-01
            • 2015-10-01
            • 2011-08-24
            • 1970-01-01
            • 2010-11-16
            相关资源
            最近更新 更多