如何在不执行代码的情况下从不同的PHP文件中获取变量?

时间:2017-06-26 01:31:50

标签: php output-buffering

我试图遍历名为$ articleContents的数组中列出的所有php文件,并从每个文件中提取变量$ articleTitle和$ heroImage。

到目前为止,我有以下代码:

$articleContents = array("article1.php", "article2.php"); // array of all file names
$articleInfo = [];
$size = count($articleContents);
for ($x = 0; $x <= $size; $x++) {
ob_start();

if (require_once('../articles/'.$articleContents[$x])) {

ob_end_clean();

    $entry = array($articleContents[$x],$articleTitle,$heroImage);

    array_push($articlesInfo, $entry);

}

问题是,循环中访问的php文件有html,我不能阻止它执行。我想从每个文件中获取变量而不在每个文件中执行html。

此外,变量$ articleTitle和$ heroImage也存在于我工作的php文件的顶部,所以我需要确保脚本知道我在外部文件中调用变量而不是现在的那个。

如果无法做到这一点,请您推荐一种替代方法吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

不要这样做。

您的PHP脚本应该适用于您的应用程序,而不适用于您的数据。对于您的数据,如果您想保持基于文件,请使用单独的文件。

有很多格式可供选择。 JSON很受欢迎。您也可以使用PHP's built-in serialization,它支持更多PHP本机类型,但不像其他框架那样可移植。

答案 1 :(得分:0)

您的问题(可能)归结为使用括号require。请参阅示例并注意here

相反,请像这样格式化代码

$articlesInfo = []; // watch your spelling here
foreach ($articleContents as $file) {
    ob_start();
    if (require '../articles/' . $file) { // note, no parentheses around the path
        $articlesInfo[] = [
            $file,
            $articleTitle,
            $heroImage
        ];
    }
    ob_end_clean();
}

更新:我已经对此进行了测试,效果很好。

答案 2 :(得分:0)

有点hacky但似乎有效:

$result = eval(
  'return (function() {?>' .
  file_get_contents('your_article.php') .
  'return [\'articleTitle\' => $articleTitle, \'heroImage\' => $heroImage];})();'
);

your_article.php类似于:

<?php

$articleTitle = 'hola';
$heroImage = 'como te va';

值在$result数组中返回。

说明:

构建一个php代码字符串,其中文章脚本中的代码包含在一个函数中,该函数返回一个包含所需值的数组。

function() {
  //code of your article.php
  return ['articleTitle' => $articleTitle, 'heroImage' => $heroImage];
}

也许您必须对<?php ?>标记展示位置的字符串进行一些调整。

无论如何,这件事很难看。我非常肯定它可以以某种方式重构。