Hello. Here, for example, there is a file with the contents - for example, "Test" and I connect it through require
and how can I get this text (Test) to a variable?
- NO! Because require (and everything like that) does not read the contents, much less RETURNS IT! - Salivan
4 answers
It looks like nailing a microscope , which would be worth plugging in scripts. In addition, we must remember that require()
will stop execution if there is no file.
Maybe better to look at file_get_contents()
?
Still:
- file_get_contents () server loads heavily. I have already tried - they said that you live in the 20th century. - n1k
- mmmmm .... exactly if the file connection is pushed to the buffering, and then everything comes out ?? ob_start (); include './test'; $ var = ob_get_contents (); ob_end_clean (); - n1k
- doesn’t look very believable - I can’t say anything - xEdelweiss
Do not complicate the life of a file_get_contents or a buffer; you can make everything easier - drive the contents of the included file into return, when connecting it in another script, return it to a variable - example:
include.php
<?php $var = 'PHP'; return $var; ?>
script.php
<?php $foo = include 'return.php'; echo $foo; // выведет 'PHP' ?>
I hope that is what was meant
- example taken from php.net - zippp
- no, not that. I will have only html code in this file and I need to drive it into a variable - n1k
- html code is text that can be represented as a string, which in turn can be a variable value, i.e. in the example above, instead of $ var = 'PHP', $ var = '<title> Start Page Title </ title>'; and you will return html if for some reason you don’t like it, use file_get_contents () - zippp
Do you really want this?
ob_start(); include 'file.html'; $html = ob_get_clean();
Without testing, I’m ready to argue that when compared, the aforementioned @xEdelweiss file_get_contents
will be faster.
Upd. And here is the comparison data ! The second answer. From fast to brake:
- file_get_contents ()
- readfile ()
- include
- Thanks a lot. It’s just that some educated people tell me that something is loading the server and I go here and as a result it turns out that it does not load anything even the other way around - n1k
- Why go from one "educated" people to others? Checking yourself is not so difficult:) @Deert, If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Sergiks
- advise a program with which you can find out the speed of the function (script) - n1k
- In the answer, the reference "data comparison" is clickable. There in the second answer are code samples. In PHP, there is a micro-time function () that returns the time with an accuracy of 1/1000 of a second. Remember it before starting the cycle of 100,000 file reads in one of the ways, and compare it with the time measured immediately after. - Sergiks
Use the template engine. It can also return the template code to the variable.