I have a requirement, according to that I need to read mail(which will be in specified format). The email would be basically in a format it includes some fields information like:
Name: xyz
Zip: 33402
Now what we need to do is to save "Name" in 'name' column and "Zip" in 'zip' column of database table.
I can read mail via IMAP through PHP script and can fetch "BODY", But I need help to find out way so that I can read the fields.
Please share any way/option of yours to do it.
If the problem really is only parsing, in this case I would recommend simple regex.
However what I do recommend is using named patterns, so you dont confuse the indexes and maby have wrong matches.
Here is a quick example:
$str = <<<body
Name: xyz
Zip: 33402
body;
if(preg_match('/(?P<name>\w+): (?P<zip>\d+)/', $str, $matches)) {
print_r($matches);
// db beeing your database connector, for example pdo
$sql = "INSERT INTO mytable (name,zip) VALUES(".$db->quote($matches['name']).",".$db->quote($matches['zip']);
echo $sql;
} else {
//mail does not correspond to pattern!
}
If your mail gets longer, use preg_match several times. Possibly for each field you want to parse separately. Because writing a huge regex if you have more fields is very hard to maintain. Also the order of fields has to be considered.
However this is all not very robust. Expecially the content of the fields has to be considered.
What if someone has a name with line breaks or commas in it.
I would really urge to consider putting the body of the mail into a better format before sinding. One that deals with escaping. For example CSV or (my favorite) JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With