doulun0651 2011-11-24 14:51
浏览 137
已采纳

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

I want to include an external file, and then get all the content, remove the only HTML on the page <br /> and replace with , and fire it into an array.

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("");

I want to load a php file from the server directory, get the HTML contents of this file and place it into a useable array.

It would look like

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

3条回答 默认 最新

  • dsadsadsa1231 2011-11-24 15:08
    关注

    Here is a working version of 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);
    ?>
    

    By using a regular expression to find the <br />, the code is able to deal with many variations such as <br>, <BR>, <BR />, <br/>, etc.

    The output is:

    Array
    (
        [0] => john_23
        [1] => john_5
        [2] => john_23
        [3] => john_5
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?