Then I guess that you have to write it yourself. But it is not a good idea, much faster and more reliable to use a "real" database backup rather than a script that reads the rows one at a time.
Oh, by the way. phpMyAdmin is a php script that does it, and you could probably integrate the correct parts in your script...