I want to read contents of a text file and insert the contents into a table This is the content of the text file
--------------------------------
Text file contents
--------------------------------
[playlist]
mode=play
Title1=Radio 1|United Kingdom
File1=http://www.test.com/0001
Title2=Radio 2 |United States
File2=http://www.test.com/0002
Title3=Radio 3|United Kingdom
File3=http://www.test.com/0003
NumberOfEntries=3
Version=2
-------------------------------
And store in a table like this
id | item | url
----------------------------------------------------------
1 | Radio 1|United Kingdom | http://www.test.com/0001
2 | Radio 2 |United States | http://www.test.com/0002
3 | Radio 3|United Kingdom | http://www.test.com/0003
How do i grab Title and File so that I can insert it into a DB table. I am using file_get_contents() to read text file.
My current code:
$content = file_get_contents("textfile.txt");
$lines = explode("
", $content);
foreach ($lines as $line) {
$row = explode("", $line);
$stmt="INSERT INTO table_1 (item, url)
VALUES
(....)";
}
Please help me. Thanks in advance.
If the file is always the same format you can parse the data and build an array
$content = file_get_contents('textfile.txt');
$lines = explode("
", $content);
$data = array();
foreach ($lines as $line) {
if (preg_match('/^(Title|File)([0-9]+)\=(.+)$/', $line, $match)) {
$data[$match[2]][$match[1]] = $match[3];
}
}
After that you can loop trough the data array and insert into the database.
foreach($data as $id => $values) {
$sql = 'INSERT INTO table_1 (item, url) VALUES ("' . $values['Title'] . '", "' . $values['File'] . '")';//The values need to be escaped!
}