The script executed without problem on my local WAMP server. My solution was to host the script on a different host (Azure), and it worked fine first time. (no special setup)
I never worked out the specific cause for this, but I'm fairly confident it's something in my shared web hosting configuration. I was trying to host my script using budget shared hosting service(Crazy Domains).
Note: Other than this, I've been happy with my host provider. But help or configuring setup to do this seems to be beyond their offering.