MAX POWER
MAX POWER

Reputation: 5448

Exporting email form data to a database

I have a form on my website that is submitted to my email address; the structure of the email is as follows:

Name: John Smith

Address 1: 1 Kings Road

Address 2: Kings Place

City: London

Post Code: SW1

Enquiry Type: General Enquiry

Website: http://www.stackoverflow.com

Email: [email protected]

Details: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

This is how it arrives to me in my inbox. I have several of these emails - and I need to export the data from these emails in to my database. I have all the fields set up in the database (name, address1, etc), so now all I need to do is extract each piece of data from the email.

I have set up a form with a textarea field - the idea being that I copy and paste the contents of the email into that textarea and then submit the form. The processing of the data will be done in the PHP script.

I am struggling to figure out how best to do this - I could do with some ideas. Thanks.

Upvotes: 0

Views: 100

Answers (2)

Qqwy
Qqwy

Reputation: 5639

The best way to split the string is by using a regular Expression.

In this case, use:

$result = preg_split( "~(\w* )?\w*\: ~", $data);

Explanation of the Regular Expression: the ~ is just the delimiter for the begin and end of the string. the first (\w* )? part matches zero or more occurrences of any amount of word(alphanumeric and _) characters followed by a space. The next w*\: matches a word followed by a : and then followed by a space.

This matches all the 'titles' of the formdata, thus splitting it as wanted. Also note that this is formatted in such a way that you don't match the : in http://example.com.

Upvotes: 0

Blender
Blender

Reputation: 298246

If the email would be coming in exactly like this each time, you could try two things:

  1. Regex. It'll be a bit nasty, but it should get the job done with enough blood.
  2. Blind parsing. I like this approach, which is what I'll try and describe.

I'd try splitting the email's body with explode("\n", $body).

Now, index of the array will contain one line of your email. You can just assign a number of characters to chop off to each line (to strip out the field name) and you are all set.

Upvotes: 1

Related Questions