How can PHP be used to automate the process of parsing and inserting structured data from a text file into a MySQL database?

To automate the process of parsing and inserting structured data from a text file into a MySQL database using PHP, you can create a script that reads the text file line by line, parses the data, and inserts it into the database using SQL queries. This can be achieved by opening the text file, reading its contents, parsing the data into individual fields, and then executing SQL INSERT queries to insert the data into the MySQL database.

<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Open the text file for reading
$filename = "data.txt";
$file = fopen($filename, "r");

// Read the file line by line
while(!feof($file)) {
    $line = fgets($file);

    // Parse the data into individual fields
    $data = explode(",", $line);

    // Insert the data into the database
    $sql = "INSERT INTO table_name (field1, field2, field3) VALUES ('$data[0]', '$data[1]', '$data[2]')";
    if ($conn->query($sql) === TRUE) {
        echo "Record inserted successfully";
    } else {
        echo "Error inserting record: " . $conn->error;
    }
}

// Close the file and database connection
fclose($file);
$conn->close();
?>