Всем привет. Помогите пожалуйста в автоматизации процесса. Есть txt файлы с них нужно импортировать данные в mysql Причем txt файлов больше 20 штук. Один txt это одна статья. Заголовок статьи должен попадать в отдельное поле в mysql. Как создавать форму добавления данных в mysql я разобрался. Вот с этим пока нет.
frui78 PHP: <?php mysql_query ("INSERT into `articles` (`id, `text`) VALUES ('', '" . $_POST['article_text'] . "');");
читать текстовый файл в массив, первый элемент массива писать в базу как заголовок, остальные - как текст?
К примеру я добавляю в mySQL статьи так: PHP: <?php $db = mysql_connect ("localhost","fruit","123"); mysql_select_db ("addarticles", $db); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1251"> <title>Untitled Document</title> </head> <body> <form name="form1" method="post" action="add_articles.php"> <p> <label>Введите заголовк статьи<br> <input type="text" name="headline" id="headline"> </label> </p> <p> <label>Введите текст статьи с тэгами<br> <textarea name="articles" id="articles" cols="60" rows="20"></textarea> </label> </p> <p> <label> <input type="submit" name="submit" id="submit" value="Добавить статью"> </label> <br> </p> </form> </body> </html> Здесь выполняется самам операция добавления: PHP: <?php $db = mysql_connect ("localhost","fruit","123"); mysql_select_db ("addarticles", $db); if (isset($_POST['headline'])) {$headline = $_POST['headline'];} if (isset($_POST['articles'])) {$articles = $_POST['articles'];} ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1251"> <title>Обработчик</title> </head> <body> <? if (isset ($headline)&&($articles)); else echo 'NO'; echo "$headline"; echo "<br>"; echo "$articles"; /*echo '<br>'; if (empty($headline)) echo "EMPTY"; else echo "Yes"; echo "<br>"; echo "$headline"; echo "<br>"; echo "<br>"; if (empty($articles)) echo "EMPTY"; else echo "Yes"; echo "<br>"; echo "$articles";*/ /*Можно заносить информацию*/ if (isset ($headline)&&($articles)) { $result = mysql_query ("INSERT INTO articles (headline,articles) VALUES ('$headline','$articles')"); if ($result == 'true') {echo "<p>Ваша статья добавлена</p>";} else {echo "<p>Ваша статья НЕ добавлена</p>";} } else { echo "<p>Вы ввели не всю информацию</p>"; } ?> </body> </html>
Теперь создание самих статей автоматизировал, большая статья разбивается на маленькие и прописывается в txt файлы (в принципе может сохранять в любом формате, в том в каком укажешь html, php, txt). Причем сохраняет уже с тэгами. Вот теперь надо указать определенную директорию где лежат все txt, и дать команду на внесение их в mySQL, чтоб сам заголовок прописать в определенное поле (он автоматом прописывается с тэгами <h3>).
Elkaz Fduch Большое спасибо за быстрый Ваш ответ. Не могли бы Вы подсказать как сделать так чтобы, можно было выбирать из указанной директории файлы, выбирать от туда данные и потом заносить их в базу.
Выбираем все находящиеся в папке файлы/дериктории: http://www.php.net/manual/ru/function.scandir.php В цикле получаем из файла данные: http://ru2.php.net/manual/ru/function.f ... ntents.php
Всем доброго времени суток. Спасибо всем кто отозвался на мой вопрос. Сам вопрос пока не решил, но есть вот пару наработок. По Вашей рекомендации akrinel учил работу array scandir () и array file(). Что получилось: PHP: <?php $dir = '/home/localhost/www/tomysql/file/'; $files1 = scandir($dir); print_r($files1); ?> <br> <br> <?php /* $homepage = file_get_contents('$files1'); echo $homepage;*/ ?> <br> <br> <?php $data = `/home/localhost/www/tomysql/investmentTXT.txt`; // 1.98 seconds $fh = fopen('/home/localhost/www/tomysql/file/investmentTXT.txt', 'r'); $data = fread($fh, filesize('/home/localhost/www/tomysql/investmentTXT.txt')); fclose($fh); // 0.00082 seconds $data = file_get_contents('/home/localhost/www/tomysql/investmentTXT.txt'); // 0.0069 seconds echo $data; ?> <br> <br> <?php $fd = fopen ("/home/localhost/www/tomysql/investmentTXT.txt", "r"); while (!feof ($fd)) { $buffer = fgets($fd, 4096); $lines[] = $buffer; } fclose ($fd); echo $buffer; ?> Есть вопрос, ну по первому скрипту то все понятно, со вторым вроде тоже, а вот третий, при добавлении echo $buffer; выводит с текста последнею строку. Будьте добры, подскажите как теперь два скрипта связать вмести. Что бы в цикле получать из файлов данные, файлы которые определил scandir (). Как я понимаю первый скрипт выбирает из директории все файлы, второй вытягивает все их содержимое, помещает их в переменную в виде массива, затем из этой переменной данные можно будет отправить для добавления в mysql.
С этой функцией разобрался, echo $buffer; надо добавлять после $buffer = fgets($fd,10000); и $lines[] = $buffer; думаю можно убрать или // //$lines[] = $buffer;. Получается так: PHP: <?php $fd = fopen ("/home/localhost/www/tomysql/investmentTXT.txt", "r"); while (!feof ($fd)) { $buffer = fgets($fd,10); echo $buffer; } fclose ($fd); ?> В результате выведется все содержимое файла. Теперь вопрос, все тот же, как поставить в цикл вывод содержимого файлов с запроса PHP: <?php $dir = '/home/localhost/www/tomysql/file/'; $files1 = scandir($dir); print_r($files1); ?> И потом добавить в Mysql.
Так пойдет? PHP: <?php /** * Импортируем данные из файлов в MySQL * * @author akrinel * @copyright Дорогие Росияне. Ну и Бендер конечно же. */ class Importer{ /** * После какого объема данных происходит запись(в байтах) */ const MAX_BUFFER_SIZE = 2097152; /** * Директория в которой лежат файлы под индексацию * * @var String */ private $dir; /** * Данные из файлов * * @var Array */ private $filesContent = array(); /** * @param String $dir директория в которой лежат файлы под индексацию */ public function __construct($dir){ $this->dir = $dir; if(!is_dir($this->dir)){ throw new Exception; } } /** * Собственно стартуем импорт * */ public function doImport(){ $files = scandir($this->dir); $bufferSize = 0; if(!empty ($files)){ foreach($files as $file){ $fileName = $this->dir.'/'.$file; if(is_dir($fileName)){ continue; } $this->filesContent[] = file_get_contents($fileName); $bufferSize += filesize($fileName); if($bufferSize >= self::MAX_BUFFER_SIZE){ $this->writeForBD(); $bufferSize = 0; $this->filesContent = array(); } } } if($bufferSize != 0){ $this->writeForBd(); } return true; } /** * Записываем в БД наши данные */ private function writeForBd(){ /* * Здесь какая-то Ваша функция в цикле обходит * данные формирует запрос и записывает их в БД */ } } ?> Пример использования: PHP: <?php $indexer = new Importer(dirname(__FILE__)); $indexer->doImport(); ?>
akrinel Спасибо большое за ответ. Как я уже писал, от выложенного скрипта я потерялся. Я на него смотрю как стадо баранов на новые ворота, не зная с какого края к нему подойти. Я он боролся с двумя функциями. Одна сканирует директорию вторая открывает файл. Можно взять их за основу. PHP: Первый <?php $dir = '/home/localhost/www/tomysql/file/'; $files1 = scandir($dir); print_r($files1); ?> Второй <?php $fd = fopen ("investment.txt", "r"); while (!feof ($fd)) { $buffer = fgets($fd, 40960); $lines[] = $buffer; echo $buffer; } fclose ($fd); ?>
Ночью откопал скрипт, должен импортировать данные, цуко бодается, правда он конвертирует CSV, ну вроде в дискрипшене написано --- Скрипт CSV/TXT Flat File to MySQL, сделал настрой пишет NOT ADDED, мож кто глянет свежим взлядом а, че ему еще надо. PHP: <? /////////////////////////////////////////////////////////////////////////// //CSV/TXT Flat File to MYSQL Database Converter V1.0 //Copyright Total Net Marketing 2002 //If you get stuck you can email me and I may be able to help [email=//paul.kovac@bigpond.com]//paul.kovac@bigpond.com[/email] //This is a free script so feel free to reuse or make changes //to suit your purposes but please do not re-distribute if you //have made changes to it. //You you want to be noted for your changes please email them to //me with your details and the changes you made and I will add //reference to you and your help in improving this script in V1.1 //that's if there ever is one. // /////////////////////////////////////////////////////////////////////////// //In the grand scheme of things I am relatively new to PHP. I recently // //needed to convert a CSV file to MYSQL. I looked through HOTSCRIPTS but // //found very little that would do, so I decided to build my own. // //Being inexperienced this took me awhile but I finally // //nailed it. Now I know the code isn't perfect but it works so I hope // //it will help you out as much as it helped me out. // /////////////////////////////////////////////////////////////////////////// //Configure the variables below! // /////////////////////////////////////////////////////////////////////////// // //THE NAME OF YOUR MYSQL DATABASE $mydatabase = "addarticles"; //THE NAME OF YOUR MYSQL TABLE $mytable = "articles"; //YOUR USERNAME TO ACCESS MYSQL $user = "fruit"; //YOUR PASSWORD TO ACCESS MYSQL $pass ="123"; //THE ADDRESS OF YOUR MYSQL SERVER $address ="localhost"; //CSV/TXT FILE THAT YOU WISH TO CONVERT $CSV = "test.txt"; //TYPES OF FIELD SEPERATORS //COMMA , //TAB \t //COLON : //SEMI-COLON ; //YOUR CSV/TXT FILE SEPERATOR $seperator = "test.txt"; /////////////////////////////////////////////////////////////////////////// //Configuration stops here! /////////////////////////////////////////////////////////////////////////// $noconnection = "Error: Could not connect to database. Please try again later!"; $notentered = "You have not entered all the required details.<br>" ."Please go back and try again."; @ $db = mysql_pconnect("$address", "$user", "$pass"); if (!$db) { echo "$noconnection<p>"; } mysql_select_db($mydatabase); $openit = file($CSV); $counter = count($openit); $filearray = file("$CSV"); echo "<center><font face=arial size=3>Total Net Marketing<br>Database Converter</font></center><p>"; for($i=0; $i<$counter; $i++) { $item = explode("$seperator", $filearray[$i]); include("query.inc"); $result = mysql_query($query); if ($result) { echo $effected_item." <font color=blue>has been added</font><br>\n"; } else { echo $effected_item." <font color=red>NOT ADDED</font><br>\n"; } } ?> вот этот $seperator = "test.txt"; -- шо ему надо, я туда название файла вписал (мож не надо было этого делать)?. перевел его как разделитель. $seperator = ","; -- это было с ним до внесения мной мутаций. :roll:
его описалово STEP 1. If you just want to get the script up and running to see how it works then open "MYSQL table structure.txt" copy the structure access MYSQL and run the query. STEP 2. Now that the table is created open "query.inc" and read through the instruction to understand how it works. STEP 3. Now open "convert.php" and run through the configuration! I have tried to make this as easy as possible to install there are only 7 variables to set. Save it. STEP 4. Upload the folder "converter" and all it's contents. Next call http://www.your_domain_name.com/converter/convert.php and if all your variable are correct then it should add the csv data to your table and tell you if it was successful or a failure for each entree. //////////////////////////////////////////////////////////////////////// IF YOU ARE USING YOUR OWN FILE AND TABLE //////////////////////////////////////////////////////////////////////// STEP 1. Read all the instructions, create your MYSQL table and configure the variables and your done; "I hope". /////////////////////////////////////////////////////////////////////////