문제

다른 페이지의 변수에서 .php 파일의 내용을 가져오고 싶습니다.

두 개의 파일이 있습니다. myfile1.php 그리고 myfile2.php.

myfile2.php

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

이제 myfile1.php의 변수에서 myfile2.php에 의해 값을 반영하고 싶습니다. Follwing 방식을 시도했지만 PHP Tag ()를 포함한 모든 내용을 취했습니다.

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

하나의 PHP 파일로 반환 된 내용을 다른 PHP 파일에 정의 된 변수로 가져올 수있는 방법을 알려주십시오.

감사

도움이 되었습니까?

해결책

당신은 사용할 수 있습니다 포함 이를위한 지침.

File 2:

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

File 1:

<?php 

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

?>

다른 팁

두 가지를 차별화해야합니다.

  • 출력을 캡처 하시겠습니까 (echo, print포함 된 파일의, ...) 및 변수 (문자열)에서 출력을 사용합니까?
  • 포함 된 파일에서 특정 값을 반환하고이를 변수로 사용 하시겠습니까? 주최자 스크립트?

포함 된 파일의 로컬 변수는 항상 귀하의 현재 범위로 이동됩니다. 주최자 스크립트 - 이것은 언급해야합니다. 이러한 모든 기능을 하나로 결합 할 수 있습니다.

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

편집하다

출력 버퍼를 사용할 때 성능 페널티에 대한 질문에 답하기 위해 빠른 테스트를 수행했습니다. 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

file1.php :

<? return 'somevalue'; ?>

file2.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;
?>

파일의 코드에서 출력을 반환하려면 편안한 API를 호출하십시오. 이러한 방식으로 AJAX Call, REST API 또는 내부 PHP 코드에 동일한 코드 파일을 사용할 수 있습니다.

컬을 설치해야하지만 출력 버퍼 또는 포함 없음이 필요하지 않으며 페이지 만 실행되어 문자열로 반환됩니다.

내가 쓴 코드를 줄게. 거의 모든 REST/웹 서버에서 작동하며 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