.php ファイルを実行して変数内の内容を取得するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/851367

質問

.phpファイルの内容を他のページの変数で取得したい。

2つのファイルがありますが、 myfile1.php そして myfile2.php.

myfile2.php

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

ここで、myfile1.php の変数内の myfile2.php によってエコーされた値を取得したいと思います。次の方法を試しましたが、php タグ () を含むすべてのコンテンツも取得します。

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

ある PHP ファイルから返された内容を、別の PHP ファイルで定義された変数に取得する方法を教えてください。

ありがとう

役に立ちましたか?

解決

使用できます 含む これを行うための指示。

ファイル 2:

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

ファイル 1:

<?php 

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

?>

他のヒント

次の 2 つのことを区別する必要があります。

  • 出力をキャプチャしますか (echo, print,...) をインクルードしたファイルの出力を変数 (文字列) で使用しますか?
  • 含まれているファイルから特定の値を返し、それらを変数として使用しますか? ホスト 脚本?

インクルードされたファイル内のローカル変数は常に、現在のスコープに移動されます。 ホスト スクリプト - これに注意してください。これらすべての機能を 1 つに組み合わせることができます。

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-feature は、特に設定ファイルを使用する場合に便利です。

config.php

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

app.php

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

編集

出力バッファ使用時のパフォーマンスの低下に関するご質問に答えるために、簡単なテストを行ってみました。1,000,000回の反復 ob_start() そして対応する $o = ob_get_clean() 私の Windows マシンでは約 7.5 秒かかります (おそらく PHP にとって最適な環境ではありません)。パフォーマンスへの影響は非常に小さいと考えるべきだと思います...

コンテンツのみが必要な場合 echo()含まれているページによって編集された場合は、出力バッファリングの使用を検討できます。

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

見る http://php.net/ob_start

私はいつも避けようとします ob_ 機能。代わりに、私は以下を使用します。

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

「実際、値を直接与えることができる戻り型のメソッドはないか探していたところです。」 - あなたは自分の質問に答えただけです。

見る http://sg.php.net/manual/en/function.include.php, 例 #5

ファイル1.php:

<? return 'somevalue'; ?>

ファイル2.php:

<?

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

?>

出力バッファを使用すると、出力したものはすべて保存され、明示的に指示するか、実行パスの終わりまでにバッファを終了/クリアしない限り、出力されません。

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

サイト全体の使用を取得したい場合は、

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

このコードを試してください

myfile1.php

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

myfile2.php

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

ファイル内のコードからの出力を返したい場合は、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;

    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top