History: Where did 'An apple a day keeps the doctor away' come from?

And is it even true?

An apple a day keeps the doctor away. We’ve all heard it, that apple-based adage our parents convinced us of in a last-ditch attempt to get some roughage in our diets. 

Apple

But where does this saying actually come from, and more to the point, is there any truth to it?

One of the earliest known examples of its use in print can be found in an 1866 edition of a Welsh magazine, called Notes and Queries, and goes something like:

Eat an apple on going to bed, and you’ll keep the doctor from earning his bread.

The idea of