Я использовал PHP 5.5.9-1ubuntu4.22. У меня есть следующий CSV-файл, который я прочитал:
Product;Category;Manufacturer;Price;hasWlan
Product 8;Category 1;Manifacturer - 9;3;f
Product 7;Category 8;Manifacturer - 1;5;t
Product 9;Category 8;Manifacturer - 1;10;t
Product 9;Category 2;Manifacturer - 7;7;f
Product 5;Category 9;Manifacturer - 2;7;t
Product 5;Category 3;Manifacturer - 7;10;t
Product 6;Category 10;Manifacturer - 4;1;t
Product 5;Category 7;Manifacturer - 2;1;t
Product 5;Category 1;Manifacturer - 6;6;t
Я хотел бы заменить следующий шаблон значениями csv:
Шаблон:
@attr(Product) has the @attr(Category) from the @attr(Manufacturer).
Требуемый результат:
Product 8 has the Category 1 from the Manufacturer - 9.
Product 7 has the Category 8 from the Manufacturer - 1.
etc.
Я попробовал следующий php-скрипт:
<?php
class StringTemplate
{
public function process($text, $singleVariable, $data) {
// 1. Replace Variables
$pattern = '@attr(' . $singleVariable . ')';
$text = str_replace($pattern, $data, $text);
// return final result
return $text;
}
}
/*******************/
/***EXAMPLE USAGE***/
/*******************/
// 1. Read in csv
$csvFile = '/home/ubuntu/workspace/src/SampleText.csv';
echo "\n";
$StringTemplate = new StringTemplate();
$template = "@attr(Product) has the @attr(Category) from the @attr(Manufacturer). ";
$row = 0;
$vars = array();
if (($handle = fopen($csvFile, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 10000, ";")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
echo $StringTemplate->process($template, $vars, $data[$c]);
}
if ($row == 0) {
$vars = $data;
echo print_r($vars) . "\n";
}
echo "####################### \n";
$row++;
}
fclose($handle);
}
Однако в настоящее время я получаю следующий вывод:
$ php src/testFile.php
@attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). Array
(
[0] => Product
[1] => Category
[2] => Manufacturer
[3] => Price
[4] => hasWlan
)
1
#######################
@attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). #######################
...
Как видите, в моем скрипте данные не заменяются.
Есть предложения, почему это так?
Я ценю ваши ответы!
@u_mulder Спасибо за ответ! Нужен ли мне еще один цикл, чтобы этот код заработал? ; /






Как ваша единственная переменная $singleVariableне является (переименуйте ее, не путайте себя и других), вы должны создать из нее массив замен. Итак, я думаю, вам следует заменить
$pattern = '@attr(' . $singleVariable . ')';
с участием:
$pattern = [];
foreach ($singleVariable as $variable) {
$pattern[] = '@attr(' . $variable . ')';
}
Остальной код функции остается прежним. Поскольку str_replace умеет работать с массивами, все должно работать.
Кроме того, вы должны исправить свой цикл while на это:
while (($data = fgetcsv($handle, 10000, ";")) !== FALSE) {
// here you get headers, there's no need to increment `$row` any more than here
if ($row == 0) {
$vars = $data;
$row++;
//echo print_r($vars) . "\n";
}
// here you replace - array of `$vars` to array of `$data`
echo $StringTemplate->process($template, $vars, $data);
}
$singleVariable- это множество.