打开文本文件读取逗号分隔值

I have the following code:

$pollids  = "pollids.txt";
$contents = file_get_contents($pollids);
list($pollid) = explode(',', $contents);
echo $pollid;

This opens a text file containing a comma separated list of text: value1,value2,value3 etc...

However it only echo's the first piece of text in the file. How can I get it to loop/fetch them all?

Secondly, once I have these values, perhaps stored in an array, can i feed them into this piece of script?

$summize = new summize;
$search = $summize->search('searchterm');
$text = $search->results[0]->text;

So that ('searchterm') is replaced by each value in the file? Again i suspect some kind of loop within a loop?

Try this:

$pollids  = "pollids.txt";
$contents = file_get_contents($pollids);
$pollfields = explode(',', $contents);

echo $pollfields[0]; // Prints the value in first "cell"
echo $pollfields[1]; // The second
echo $pollfields[2]; // And so on

Or, in a loop:

foreach($pollfields as $field) {
    echo $field;
}

explode creates an array of fields separated by ,, so $pollfields is an array of those fields, and you can feed them to your second snippet like this:

$summize = new summize;
foreach($pollfields as $field) {
    $search = $summize->search($field);
}
$text = $search->results[0]->text;

Without knowing more of how summize works, that should be what you need.

Use fgetcsv.

EDIT: explode won't work if values contain e.g. commas enclosed in quotes.

Check out the function fgetcsv

This snippet of code is also from that page of documentation: (Example #1 Read and print the entire contents of a CSV file)

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>
";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />
";
        }
    }
    fclose($handle);
}
?>
$pollids  = "pollids.txt";
$contents = file_get_contents($pollids);

$results = preg_split("/\s+|,/", $contents);
$summize = new summize;

for($i=0;$i<count($results);$i++)
{
echo $results[$i]:

$search[$i] = $summize->search($results[$i]);
$text[$i] = $search[$i]->results[$i]->text;
}

print_r($results);
print_r($search);
print_r($text);

$fantasy5 = explode(",",file_get_contents($_SERVER['DOCUMENT_ROOT']."/numbers.txt"));

shuffle($fantasy5);

for ($num = 1; $num <= 5; $num+=1) {echo $fantasy5[$num]."-";}

//the output will be five random numbers separated by a dash

==================================================

and the contents of the text file would be just numbers like this:

3, 8, 26, 37, 46, 8, 30, 35, 38, 41, 3, 9, 13, 20, 28, 10, 20, 21, 23, 36, 4, 23, 25, 33, 42, 1, 16, 26, 45, 46