Come eseguire e ottenere il contenuto di un file .php in una variabile?
-
21-08-2019 - |
Domanda
Voglio ottenere il contenuto di un file .php in una variabile in altra pagina.
Ho due file, myfile1.php
e myfile2.php
.
myfile2.php
<?PHP
$myvar="prashant"; //
echo $myvar;
?>
Ora voglio ottenere il valore eco il myfile2.php in una variabile in myfile1.php, ho cercato il modo follwing, ma il suo prendendo tutti i contenuti tra cui tag php () anche.
<?PHP
$root_var .= file_get_contents($_SERVER['DOCUMENT_ROOT']."/myfile2.php", true);
?>
Ti prego, dimmi come posso contenuto restituito da un file PHP in una variabile definita in un altro file PHP.
Grazie
Soluzione
È possibile utilizzare il direttiva include per fare questo.
File 2:
<?php
$myvar="prashant";
?>
File 1:
<?php
include('myfile2.php');
echo $myvar;
?>
Altri suggerimenti
Bisogna fare due cose:
- Vuoi catturare l'output (
echo
,print
, ...) del file incluso e utilizzare l'uscita in una variabile (stringa)? - Vuoi tornare certi valori dai file inclusi e li usa come una variabile nel vostro host lo script?
Le variabili locali nei file inclusi siano sempre essere spostati l'attuale portata del host di script - questo va ricordato. È possibile combinare tutte queste caratteristiche in un unico:
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"
Il return
-. Caratteristica è utile soprattutto quando si utilizzano i file di configurazione
config.php
return array(
'host' => 'localhost',
....
);
app.php
$config = include 'config.php'; // $config is an array
Modifica
Per rispondere alla tua domanda circa la pena di prestazioni quando si utilizzano i buffer di uscita, ho fatto alcuni test rapido. 1.000.000 iterazioni del ob_start()
e il corrispondente $o = ob_get_clean()
impiegare circa 7,5 secondi sulla mia macchina Windows (probabilmente non il migliore ambiente per PHP). Direi che l'impatto sulle prestazioni è da considerarsi piuttosto piccolo ...
Se si voleva solo il contenuto echo()
'ed dalla pagina inclusa, si potrebbe considerare l'utilizzo di buffer di uscita:
ob_start();
include 'myfile2.php';
$echoed_content = ob_get_clean(); // gets content, discards buffer
cerco sempre di evitare di ob_
funzioni. Invece, io uso:
<?php
$file = file_get_contents('/path/to/file.php');
$content = eval("?>$file");
echo $content;
?>
"In realtà stavo solo cercando che Esiste un metodo tipo di ritorno che può direttamente dammi il valore" - Hai appena risposto alla tua domanda
.http://sg.php.net/manual/en/function .include.php , Esempio # 5
file1.php:
<? return 'somevalue'; ?>
file2.php:
<?
$file1 = include 'file1.php';
echo $file1; // This outputs 'somevalue'.
?>
È possibile utilizzare buffer di uscita, che conterrà tutto quello che in uscita, e non stamparlo a meno che non si dica esplicitamente, o non / chiaro fine i buffer entro la fine del percorso di esecuzione.
// 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 si desidera ottenere tutto l'uso del sito da
<?php
$URL = 'http://www.example.com/';
$homepage = file_get_contents($URL);
echo $homepage;
?>
Si prega di provare questo codice
myfile1.php
<?php
echo file_get_contents("http://domainname/myfile2.php");
?>
myfile2.php
<?PHP
$myvar="prashant";
echo $myvar;
?>
Se si desidera restituire l'output di codice in un file, semplicemente effettuare una chiamata API RESTful ad esso. In questo modo, è possibile utilizzare lo stesso file di codice per le chiamate ajax, API REST, o per il vostro codice PHP interno.
Si richiede cURL essere installato ma nessun buffer d'uscita o non comprende, solo la pagina eseguito e restituito in una stringa.
Ti darò il codice che ho scritto. Funziona con quasi tutti i server REST / web (e funziona anche con Equifax):
$return = PostRestApi($url);
o
$post = array('name' => 'Bob', 'id' => '12345');
$return = PostRestApi($url, $post, false, 6, false);
Ecco la funzione:
/**
* 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;
}
}