I eventually figured it out I didn't initialize $resp before I used it. So I've now got
$resp = null;
before the start of the IF statement and the code is now working correctly.
That's what I get for copy/pasting Google's code and not checking it carefully!