PHP & Salesforce API - get email address from ownerId

I'm blogging this because it took me nearly a whole day to find the answer on how to do this, as it doesn't appear to be well documented anywhere.

All of this is assuming you already have a script that connects to the Salesforce API using wsdl.

So, if you need to get the email address for the "owner" of an account, lead or contact record - first you need the ownerId - which is an 18 digit string, then throw it at this function..

function getemailfromownerid($OwnerId)
// This function gets the email address for the user ID provided (matched from OwnerId)
    error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    require_once ('SforcePartnerClient.php');
    require_once ('SforceHeaderOptions.php');

        // salesforce login and wsdl
        $wsdl = 'partner.wsdl.xml';
        $userName = "username";
        $password = "password";

        // connect to salesforce
        $client = new SforcePartnerClient();
        $loginResult = $client->login($userName, $password);

        $query = "select Email from user where Id = '" . $OwnerId ."'";

        // Run the query
        $response = $client->query($query);

        // Get the size of the response. If it's zero we can assume there's no data for that record
        if ($rsize==0)
            return false;
            foreach ($response->records as $record)
                return $record->fields->Email;


    catch (Exception $e)

        // Output exception
        echo $e;


And that's it - it should return the email address if there is one, and false if not.