PHP GMAIL Contacts XML Parsing with DOMDocument and cURL

南楼画角 提交于 2019-11-30 09:27:12

Have a look at DOMDocument and DOMXPath. In order to get nodes that are part of a particular namespace, like the email node which is part of the gd namespace, you need to register the namespace with the DOMXPath object using DOMXPath::registerNamespace(). The namespace URI can usually be found at the top of the XML document.

Example:

$doc = new DOMDocument;
$doc->recover = true;
$doc->loadXML($result);

$xpath = new DOMXPath($doc);
$xpath->registerNamespace('gd', 'http://schemas.google.com/g/2005');

$emails = $xpath->query('//gd:email');

foreach ( $emails as $email )
{
  echo $email->getAttribute('address');

  // To get the title.
  // This could also be done using XPath.
  // You can also use ->nodeValue instead of ->textContent.
  echo $email->parentNode->getElementsByTagName('title')->item(0)->textContent;
}

In the example above, $result is the result of $result = curl_exec($ch);.

ankkuboss
$url = 'https://www.google.com/m8/feeds/contacts//full?max-results='.$max_results.'&oauth_token='.$accesstoken.'&alt=json&updated-min=2007-03-16T00:00:00';
function curl_file_get_contents($url)
{

$curl = curl_init();
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
//The URL to fetch. This can also be    set    when initializing a session with curl_init().
curl_setopt($curl,CURLOPT_URL,$url);    
curl_setopt($curl, CURLOPT_HTTPHEADER,array('GData-Version: 2.0'));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);    //The number of seconds to wait while trying to connect.    
curl_setopt($curl,CURLOPT_HTTPGET,true);
curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);  //The contents of the "User-Agent: " header to be used in a HTTP request.
//curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header.
//curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);    //To automatically set the Referer: field in requests where it follows a Location: redirect.
curl_setopt($curl, CURLOPT_TIMEOUT, 10);    //The maximum number of seconds to allow cURL functions to execute.
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);    //To stop cURL from verifying the peer's certificate.

$contents = curl_exec($curl);

curl_close($curl);
return $contents;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!