获取解析的PHP文件

时间:2012-02-27 14:45:23

标签: php

我试图在解析后获取PHP文件的内容,然后将其存储在变量中。 除了这个例子之外,我无法通过Google获得任何有用的信息:

ob_start();
include $file;
$content = ob_get_clean();

但是这会将内容作为纯文本返回,即:<?php?>标记仍然存在,标记之间的所有代码都不会被解析。

所以我想知道,我该怎么做呢?


更新 这是包含的文件的内容:

Testcontent

<?php echo 'This should be parsed, right?'; ?>

5 个答案:

答案 0 :(得分:5)

我几年前使用这个函数作为一种模板引擎,它似乎做你需要的 - 传递一个带有一些PHP代码的字符串,它将返回它并执行PHP。令人惊讶的是,它仍然有效: - )

function process_php( $str )
{
    $php_start = 0;

    $tag = '<?php';
    $endtag = '?>';

    while(is_long($php_start = strpos($str, $tag, $php_start)))
    {
        $start_pos = $php_start + strlen($tag);
        $end_pos = strpos($str, $endtag, $start_pos); //the 3rd param is to start searching from the starting tag - not to mix the ending tag of the 1st block if we want for the 2nd

        if (!$end_pos) { echo "template: php code has no ending tag!", exit; }
        $php_end = $end_pos + strlen($endtag);

        $php_code = substr($str, $start_pos, $end_pos - $start_pos);
        if( strtolower(substr($php_code, 0, 3)) == 'php' )
            $php_code = substr($php_code, 3);

        // before php code
        $part1 = substr($str, 0, $php_start);

        // here set the php output
        ob_start();
        eval($php_code);
        $output = ob_get_contents();
        ob_end_clean();

        // after php code
        $part2 = substr($str, $php_end, strlen($str));

        $str = $part1 . $output . $part2;
    }
    return $str;
}

答案 1 :(得分:1)

如果您可以修改$file,请在其中使用return。 否则cURL它(打开像浏览器一样的网页)。

答案 2 :(得分:1)

根据Tyil的最后评论,他希望在变量中整个php文件:

  

Tyil,如果我的包含文件如下所示:<?php echo 'test stuff'; $foo = 'one';。 $ content包含什么以及如果我尝试从包含文件访问$ foo会发生什么?

     

@MikeB $ content包含包含文件中的字符串<?php echo 'test stuff'; $foo = 'one';. var_dump($foo);,返回NULL。

<?php
$file = 'include.php';
$content = file_get_contents($file);
var_dump($content); // (string) "<?php echo 'This should be parsed, right?'; $foo = 'one'; ?>"

include.php:

<?php echo 'This should be parsed, right?'; $foo = 'one'; ?>

答案 3 :(得分:0)

这绝对有效。它对我有用:

[ghoti@pc ~/tmp]$ cat file1.php 
#!/usr/local/bin/php
<?php

$file="file2.php";
include($file);

[ghoti@pc ~/tmp]$ cat file2.php 
<?php echo "This should be parsed, right?\n"; ?>
[ghoti@pc ~/tmp]$ ./file1.php 
This should be parsed, right?
[ghoti@pc ~/tmp]$ 

您可能希望查看包含的文件(在$file中命名)并查看在初始<?php之后是否存在可能导致其不被解释为PHP脚本的奇怪字符

要查看文件中的内容的十六进制转储(以便您可以看到实际跟随<?php的字符而不是编辑器中显示的内容),请使用:od -c filename.php | less

答案 4 :(得分:0)

为此,您必须使用cURL。

好吧,如果你想有效地做到这一点,无论如何。

我知道我已经晚了好几年了,但我也在寻找这个问题的解决方案,我想分享解决方案。请记住,虽然这个脚本确实可以解析PHP HTML页面,但通过Web协议下载速度非常慢,至少在我的测试中是这样。

function GetHTMLPage($url)
{
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

...不要感谢我。感谢David Walsh。 (https://davidwalsh.name/curl-download

相关问题