PHP Loop - Извлечение данных из CSV и массива с эхо HTML - PullRequest
1 голос
/ 19 октября 2011

Это полностью экспериментальный вопрос, но если ответ на него, я сэкономлю часы ручной разметки HTML.

Теоретически это должно сработать, но я могу оценить совет, если я говорю мусор.

Мне нужен цикл для извлечения данных столбцов из столбцов электронной таблицы CSV и отображения их в HTML-разметке.

Я не могу написать PHP, но так я представляю себе работу цикла ...

<?php

    // here it needs to load the CSV file and get the column data and output them as variables (I guess)

echo <div id="interactive-map">

    // here a loop needs to begin to output this line off HTML...
    // with the arrayed variables...

<div id="[varible-1]" class="[varible-2]" title="[varible-3]"><span>[varible-3]</span></div>

    // loop finished once no more rows left in CSV

echo </div>

?>

Таким образом, результат должен выглядеть следующим образом ...

<div id="interactive-map">

    <div id="1" class="free" title="Uber"><span>Uber</span></div>
    <div id="2" class="free" title="Howdy"><span>Howdy</span></div>
    <div id="3" class="free" title="Love"><span>Love</span></div>
    <div id="4" class="free" title="Gimme"><span>Gimme</span></div>
    <div id="5" class="free" title="Totally"><span>Totally</span></div>
    <div id="6" class="free" title="Spank"><span>Spank</span></div>

</div>

CSV-файлы выглядят так ...

http://www.motocom.co.uk/test/varible.jpg

Любая помощь или совет были бы ПО-НАСТОЯЩЕМУ удивительными! Спасибо

// ОБНОВЛЕНИЕ ПОД НИЖЕ ОТВЕТА

Мой CSV ниже рассматривается как текст ...

id,class,name
1,free,Uber
2,free,Howdy
3,free,Love
4,free,Gimme
5,free,Totally
6,free,Spank

PHP ниже ...

    <?php

        $file = fopen('file.csv', 'r');
        $fields = array();

        if ($file) {
        while (($data = fgetcsv($file)) !== false) {

            if(empty($fields)) {
                $fields = $data;
                    continue;
                }


            $row = array_combine($fields, $data);

            $output = sprintf("% is ID, % is CLASS, % is NAME",
                $row['id'],
                $row['class'],
                $row['name']);

            echo $output;

            }

        fclose($file);
    }

?>

Не совсем нормально работает, что я делаю не так?

Что касается добавления HTML, я поместил пометку внутри, где находится отраженный текст, и он запутался: - /

Это эхо, но не нужная информация от CSV.

1 Ответ

2 голосов
/ 19 октября 2011

Чтобы прочитать файл, проще всего использовать встроенный fgetcsv в цикле.Вы можете создать свой собственный код синтаксического анализа, но это действительно неблагодарная работа, чтобы заставить его вести себя корректно в присутствии разделителей полей и экранированных символов.

После чтения имен полей CSV (первая итерация) и их значенийдля каждой строки (последующих итераций) вы можете использовать sprintf или vsprintf, чтобы легко создать строку HTML для вывода.

Например:

$file = fopen('php://stdin', 'r'); // or open any other file you want
$fields = array(); // this holds the name of the fields, read from the 1st row

if ($file) {
    while (($data = fgetcsv($file)) !== false) {
        // If this is the first row, we assume it holds field names.
        // So just remember what they are and loop to the next.
        if(empty($fields)) {
            $fields = $data;
            continue;
        }

        // Subsequent rows are assumed to contain data.
        // array_combine associates the data in the current row with the field
        // names from the first row, allowing us to refer to them using those
        // names and be independent of the order the fields appear in the input.
        $row = array_combine($fields, $data);

        // Format output conveniently with sprintf
        $output = sprintf("%s is %d years old.\n",
                          $row['name'],
                          $row['age']);
        echo $output;
    }
    fclose($file);
}

увидеть его в действии .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...