Do you want something like this?
$content = "Name
Street
City
This
is
some
text
Name2
Street2
City2
Something
else
string";
//$content = file_get_contents("try1.txt");
//$link = mysqli_connect("localhost", "dbuser", "dbpass", "dbname");
$string = str_replace("", '', $content);
$blocks = explode("
", $string);
foreach ($blocks as $block) {
$lines = explode("
", $block);
$name = $city = $street = $text = "";
if (!empty($lines[0])) {
$name = $lines[0];
}
if (!empty($lines[1])) {
$street = $lines[1];
}
if (!empty($lines[2])) {
$city = $lines[2];
}
if (!empty($lines[3])) {
for ($i=3; $i < count($lines); $i++) {
$text .= " " . $lines[$i];
}
$text = ltrim($text," ");
}
var_dump ($name);
var_dump ($street);
var_dump ($city);
var_dump ($text);
echo '----------------------------'."<br />";
/*
$sql = "INSERT INTO `table` (`name`, `street`, `city`, `text`)"
. " VALUES ('".mysqli_real_escape_string($link, $name)."',"
. "'".mysqli_real_escape_string($link, $street)."',"
. "'".mysqli_real_escape_string($link, $city)."',"
. "'".mysqli_real_escape_string($link, $text)."')";
mysqli_query($link, $sql);
*
*/
}
Output is
string 'Name' (length=4)
string 'Street' (length=6)
string 'City' (length=4)
string 'This is some text' (length=17)
----------------------------
string 'Name2' (length=5)
string 'Street2' (length=7)
string 'City2' (length=5)
string 'Something else string' (length=21)
----------------------------
NOTE:
So what you need to do:
Remove the $content
and uncomment that row, where file_get_contents
is.
Uncomment the $link
row, and set your connection parameters.
Remove var_dump
s, and echo "-----"
lines.
Uncomment the rest.
In this example, I've used the mysqli
as procedural style, check the document for PDO
or mysqli
how to use them OOP style.