I am currently trying to pull information from the google contacts api. Using the sample code provided in the libraries:
$response = json_encode(simplexml_load_string($val->getResponseBody())); $result = json_decode($response, true);
the simplexml_load_string
function does not pick up on namespaces. Looking at php.net and how to add the parameters I am a little lost.
$xml = json_encode(simplexml_load_string(null, $val->getResponseBody(), null, 'gd', true));
event with trying to pull the ‘gd’ namespace from my xml string I am receiving an error. Is there anyone who can assist in this?
The output error is this:
simplexml_load_string() expects parameter 2 to be a class name derived from SimpleXMLElement
But on top of this error it also correctly prints the info I want…I am confused.
Example of info I need to pull:
<gd:extendedProperty xmlns:gs='http://schemas.google_apps_sync.com' name='google_apps_sync'> <gs:em_odn1>awalker@xxxxx.com</gs:em_odn1> <gs:em_dn1>First Name Last Name</gs:em_dn1> <gs:em_ad1>awalker@xxxxxxxxx.com</gs:em_ad1> <gs:em_t1>SMTP</gs:em_t1> <gs:f_c>32791</gs:f_c> <gs:f>Last, First</gs:f> </gd:extendedProperty>
EDIT
$xmlResponse = simplexml_load_string($val->getResponseBody(), null, 0, 'gd', true); $xmlResponse->registerXPATHNamespace('gd', 'http://schemas.google_apps_sync.com'); $xmlResponse->registerXPATHNamespace('gs', 'http://schemas.google_apps_sync.com/contact/2008');
The above code allows me to access the namespaces that I need, but only one at a time….for instance:
$email = json_encode($xmlResponse->xpath('//gd:email'), true)); $postal = json_encode($xmlResponse->xpath('//gd:postalAddress'), true); $name = json_encode($xmlResponse->xpath('//gs:em_dn1'), true);
if I print these variables I get the respective information I need, but is there not a way for me to access the original $xmlResponse
variable after I have initiated the namespaces that I want?
ex:
json_decode($xmlResponse, true);
Won’t give me the xml information with the namespaces I have defined.
Advertisement
Answer
I found after hours of combing info on stackoverflow and relatively undocumented on google… if you add ?alt=json
to the end of your contacts api uri you will receive the response in JSON!