PHP包括外部文件并生成一个数组

时间:2011-11-24 14:51:44

标签: php arrays include

我想要包含一个外部文件,然后获取所有内容,删除页面<br />上的唯一HTML并替换为,并将其激活为数组。

datafeed.php

john_23<br />
john_5<br />
john_23<br />
john_5<br />

grabber.php

<?php
// grab the url
include("http://site.com/datafeed.php");

//$lines = file('http://site.com/datafeed.php);

// loop through array, show HTML source as HTML source.
foreach ($lines as $line_num => $line) {

    // replace the <br /> with a ,
    $removeBreak = str_replace("<br />",",", $removeBreak);
    $removeBreak = htmlspecialchars($line);
    // echo $removeBreak;
}

// fill our array into string called SaleList
$SaleList = ->array("");

我想从服务器目录加载一个php文件,获取该文件的HTML内容并将其放入可用的数组中。

看起来像

$SaleList = -getAndCreateArray from the file above >array("");
$SaleList = ->array("john_23, john_5, john_23");

3 个答案:

答案 0 :(得分:1)

以下是grabber.php的工作版本:

<?php
function getSaleList($file) {
    $saleList = array();
    $handle = fopen($file, 'r');
    if (!$handle) {
        throw new RuntimeException('Unable to open ' . $file);
    }
    while (($line = fgets($handle)) !== false) {
        $matches = array();
        if (preg_match('/^(.*?)(\s*\<br\s*\/?\>\s*)?$/i', $line, $matches)) {
            $line = $matches[1];
        }
        array_push($saleList, htmlspecialchars($line));
    }
    if (!feof($handle)) {
        throw new RuntimeException('unexpected fgets() fail on file ' . $file);
    }
    fclose($handle);
    return $saleList;
}

$saleList = getSaleList('datafeed.php');

print_r($saleList);
?>

通过使用正则表达式查找<br />,代码可以处理许多变体,例如<br><BR><BR />,{{1}等等。

输出结果为:

<br/>

答案 1 :(得分:1)

你似乎没有掌握包含的内容。

如果要使用PHP代码处理某些文件的内容,则include是错误的构造 - 您应该使用file()或file_get_contents()。

即。使用您在问题中注释掉的代码行。

where include是要使用的正确构造....你永远不应该直接包含远程文件 - 它的 MUCH 比本地文件系统读取的速度慢 - 并且非常不安全。有时候从远程位置获取文件并在本地缓存它是有意义的。

你不应该在包含文件中使用内联HTML或PHP代码(PHP变量/条件表达式中的html,以及PHP定义/ class / function / include / require都可以)。

答案 2 :(得分:0)

你可能需要这样的东西吗?

$file = file_get_contents('newfile.php');
echo str_replace("<br>", ",", $file);

但是我没有得到你试图插入数组的内容......

相关问题