Reading unstructured data using PHP into MySQL Database Problem
I have the following PHP code that reads in data from a formatted text file, with data separated by commas.
// Create database gameDB
if (mysql_query('create database gameDB', $connection)) {
echo "Database gameDB created successfully.\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n:";
}
// select which database to use
mysql_select_db('gameDB', $connection);
// create table xyzcoord if it doesn't already exist
mysql_query开发者_JAVA技巧('CREATE TABLE IF NOT EXISTS xyzcoord (
Frame varchar(100),
X varchar(100),
Y varchar(100),
Z varchar(100))', $connection);
$wx = array_map('trim',file("20-frames-xyz-coordinates.txt"));
$newwx = array();
foreach($wx as $i => $line)
{
if ($i > 1)
{
$tmp = array_filter(explode(' ',$line));
$q = "insert into xyzcoord (Frame, X, Y, Z) values ('" . implode("','",$tmp) . "')";
$rw = mysql_query($q) or die("Problem with the query: $q<br>" . mysql_error());
}
}
?>
My problem is I have a different text file I need to read in where the data is unstructured in the format below, for 60 frames.
(new line) Frame_0100
(new line) X_coordinates
(new line) 23.90,23.90,23.94,23.98,24.02,24.02,24.06
(new line) Y_coordinates
(new line) 5.55,6.15,5.55,5.55,5.51,5.55,5.51
(new line) Z_coordinates
(new line) 0.00,0.00,0.00,0.00,0.00,0.00,0.00
(new line)
(new line) Frame_0101
(new line) X_coordinates
(new line) 23.90,23.90,23.94,23.98,24.02,24.02,24.06
(new line) Y_coordinates
(new line) 5.55,6.15,5.55,5.55,5.51,5.55,5.51
(new line) Z_coordinates
(new line) 0.00,0.00,0.00,0.00,0.00,0.00,0.00
(new line)
(new line) Frame_0102
(new line) X_coordinates
(new line) 23.90,23.90,23.94,23.98,24.02,24.02,24.06
...etc
I am hoping to read in this data that is not already formatted, and store it in MySQL DB into tables. Im not sure how I can read the data in the format its in using PHP. I have considered using JSON. Any help is appreciated.
I'm assuming that the first two lines are blank and then the data starts uninterrupted on line 3 (index = 2); the numbers at the top will have to be changed if that is mistaken. Otherwise, replace your foreach loop with this and it should work:
foreach($wx as $i => $line)
{
if ($i > 1 and ($i-2)%4 == 0)
{
$q = "insert into xyzcoord (Frame, X, Y, Z) values ('" . $line . str_replace('X_coordinates ','',$wx[$i+1]) . str_replace('Y_coordinates ','',$wx[$i+2]) . str_replace('Z_coordinates ','',$wx[$i+3]) . "')";
$rw = mysql_query($q) or die("Problem with the query: $q<br>" . mysql_error());
}
}
精彩评论