【问题标题】:php- just one generated code displays wronglyphp-只有一个生成的代码显示错误
【发布时间】:2018-06-01 08:35:06
【问题描述】:

我有一个代码可以列出我所有的目录,没有扩展名,它运行良好。问题是当我想在之前和之后添加一些 php 时,将我的 <?php ?> 转换为 <!-- -->。我不知道为什么。 有什么想法吗?

   <?php
    $variables = '';
    $handle = '';
    $variablesfile = '';
    // open my directory
    if ($handle = opendir($_SERVER['DOCUMENT_ROOT'].'/mvi/index/graphic-documents/sozie/variables/')) {
        // list directory contents
        while (false !== ($variablesfile = readdir($handle))) {
            // exeptions
            if (($variablesfile != ".")
            && ($variablesfile != "..")
            && ($variablesfile != "index.php")
            && ($variablesfile != "compiler.php")
            && ($variablesfile != ".DS_Store"))

            // only grab file names
            if (is_file($_SERVER['DOCUMENT_ROOT'].'/my/path/'. $variablesfile)) {
                $file_name = $variablesfile;
                $file_array = explode('.',$file_name);
                $extension = count($file_array) - 2;
                $no_extension = substr($file_name,0,strlen($file_array[$extension]));

                // creation of php code 
                $variables .= '<?php $'.$no_extension.' = file_get_contents($_SERVER["DOCUMENT_ROOT"]."/my/path/'.$no_extension.'.txt")  ; ?>'. "\n" ; 
            }
        }

        closedir($handle);

        echo $variables ;

    }
    ?>

检查员的结果:

应该是什么

<?php $variable = file_get_contents($_SERVER["DOCUMENT_ROOT"]."/my/path/variable.txt")  ; ?>

<!-- ?php $variable = file_get_contents($_SERVER["DOCUMENT_ROOT"]."/my/path/variable.txt")  ; ? -->

如果我从 Chrome 检查我的源代码,&lt;?php ?&gt; 显示良好.....

其他地方一切正常。我检查了我的 apache,我在 localhost 中运行。所以在那方面一切正常。

【问题讨论】:

  • 当您说“检查员”时,您的意思是您的客户? &lt;?php 对您的浏览器毫无意义。它被解释为评论,因为它没有其他意义。
  • yes... 在 Chrome 检查器中
  • 您无法将 PHP 代码发送到您的浏览器。您必须在 PHP 环境中执行它。我不确定为什么你有 PHP 代码发出 PHP 代码。也许你能解释一下原因。
  • 这里的关键是你不能只发出&lt;?php 并让浏览器处理,因为它不能,Chrome 不知道 PHP 是什么,而且很可能永远不会。您需要返回 HTML,或者在您发送回 JSON 数据的情况下,无论如何都需要返回格式良好的内容。 PHP 代码不会削减它。

标签: php html variables comments


【解决方案1】:

请记住,您只有一个镜头和一个镜头,只是为了渲染出您在处理此请求时需要做的任何事情。因此,您必须立即执行呈现响应所需的任何代码。

尝试通过定义关联数组来捕获结果:

$results = array();

然后使用 $no_extension 变量作为键将数据插入到该结构中:

$results[$no_extension] = file_get_contents($_SERVER["DOCUMENT_ROOT"]."/my/path/$no_extension.txt");

所以最后你可以对这些数据做任何你想做的事情。

不要忘记 PHP 可以并且将会在双引号字符串中插入变量,例如 $no_extension。如果您尝试根据其他字符串组合字符串,这可以简化您的代码,避免重复连接。

【讨论】:

  • 是的,这很明智...我做梦太多了 =)))))) 并且效率不高
  • @Odjone 在网络上工作时很容易混淆上下文。有时你在 HTML 中编写 SQL,在 PHP 中编写 CSS,所以基本上有四种不同的语言在使用它们自己的语法。保持你的方位可能是一个挑战。
猜你喜欢
  • 2012-05-29
  • 2013-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-30
  • 2014-09-08
  • 2016-01-19
  • 2011-04-04
相关资源
最近更新 更多