blogger_使用Blogger数据API将Blogger内容与PHP应用程序集成

blogger

您可能听说过Blogger,这是一个免费的博客平台,可让您轻松创建个人Web日志并发布有关任何主题的帖子。 自1999年以来一直存在的Blogger是网络上最早的博客平台之一。 它由Google购买,并集成到Google的免费服务套件中。

使用Blogger,对于没有特定技术知识的人来说,创建和维护自己的Weblog很容易。 Blogger:

  • 带有一些预定义的模板和布局
  • 支持评论,访问控制和移动设备
  • 与其他服务(例如Twitter,Google AdSense等)紧密集成,以实现内容共享和货币化。

简而言之,Blogger提供了发布博客所需的一切,而不必担心技术细节。

但是Blogger不仅使用户感兴趣。 与许多其他Google服务一样,Blogger拥有一个开发人员API,可让您掌握该服务的内幕并提取内容以创建自己的自定义应用程序和混搭。 您可以通过任何支持XML的开发工具包访问遵循REST模型的Blogger数据API。 它已经具有许多常用编程语言的客户端库,包括我最喜欢的语言:PHP。

在本文中,了解Blogger数据API,以及如何将Blogger内容与PHP应用程序集成和使用。 许多示例将指导您完成以下操作:

  • 连接并验证API
  • 检索博客列表和博客供稿
  • 添加,更新和删除内容
  • 处理博客评论

关键概念

在开始学习PHP代码之前,本节将概述Blogger数据API。 与所有基于REST的服务一样,API接受包含一个或多个XML编码的输入参数的HTTP请求,并返回可以在任何支持XML的客户端中解析的XML编码的响应。 使用Blogger API,响应始终由包含所请求信息的Atom或RSS feed组成。

Blogger具有公共和私人供稿。 您无需身份验证即可访问公共供稿,例如博客中的帖子列表。 私人供稿需要身份验证。 例如,私人供稿需要身份验证才能对博客文章或评论执行添加或更新操作。 本文中的示例演示了两种提要。

为了充分利用本文,您应该拥有一个Blogger帐户,该帐户至少包含一个博客和一个帖子。 如果您还没有,则可以登录Blogger(请参阅参考资料 ),创建一个新博客,并在其中添加新帖子以进行测试。 登录后,尝试在网络浏览器中访问URL http://www.blogger.com/feeds/default/blogs 。 您应该看到类似于清单1的内容

清单1. Blogger metafeed
<?xml version='1.0' encoding='UTF-8'?>
<?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?>
<feed xmlns='http://www.w3.org/2005/Atom' 
 xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'>
  <id>tag:blogger.com,1999:user-12345USERIDHERE12345.blogs</id>
  <updated>2011-09-02T03:35:34.547Z</updated>
  <title type='text'>V Vaswani's Blogs</title>
  <link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' 
   href='http://www.blogger.com/feeds/12345USERIDHERE12345/blogs'/>
  <link rel='self' type='application/atom+xml' 
    href='http://www.blogger.com/feeds/12345USERIDHERE12345/blogs'/>
  <link rel='alternate' type='text/html' 
    href='http://www.blogger.com/profile/12345USERIDHERE12345'/>
  <author>
    <name>V Vaswani</name>
    <email>noreply@blogger.com</email>
  </author>
  <generator version='7.00' uri='http://www.blogger.com'>Blogger</generator>
  <openSearch:totalResults>1</openSearch:totalResults>
  <openSearch:startIndex>1</openSearch:startIndex>
  <openSearch:itemsPerPage>25</openSearch:itemsPerPage>
  <entry>
    <id>tag:blogger.com,1999:user-12345USERIDHERE12345.blog
     -12345BLOGIDHERE12345</id>
    <published>2008-02-19T23:30:41.755-08:00</published>
    <updated>2011-09-01T04:01:19.669-07:00</updated>
    <title type='text'>V Vaswani's Blog</title>
    <summary type='html'></summary>
    <link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/
     12345USERIDHERE12345/blogs/12345BLOGIDHERE12345'/>
    <link rel='alternate' type='text/html' href='http://vvaswani.blogspot.com/'/>
    <link rel='http://schemas.google.com/g/2005#feed' 
     type='application/atom+xml' 
     href='http://vvaswani.blogspot.com/feeds/posts/default'/>
    <link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml'
     href='http://www.blogger.com/feeds/12345BLOGIDHERE12345/posts/default'/>
    <link rel='http://schemas.google.com/blogger/2008#template' 
     type='application/atom+xml' 
     href='http://www.blogger.com/feeds/12345BLOGIDHERE12345/template'/>
    <link rel='http://schemas.google.com/blogger/2008#settings' 
     type='application/atom+xml' 
     href='http://www.blogger.com/feeds/12345BLOGIDHERE12345/settings'/>
    <author>
      <name>V Vaswani</name>
      <email>noreply@blogger.com</email>
    </author>
    <gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' 
     name='IS_PUBLIC_BLOG' value='true'/>
    <gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' 
     name='PICASAWEB_ALBUM_ID' value='0'/>
  </entry>
</feed>

清单1中的元供稿提供了与当前经过身份验证的用户相关联的所有博客的列表。 它以<feed>元素作为根元素打开。 <feed>元素包含:

  • <link>元素,其中包含供稿的不同版本的URL
  • <author>元素,用于指定帐户所有者
  • <openSearch>元素,其中包含摘要统计信息

最外面的<feed>元素包含一个或多个<entry>元素,每个元素代表一个博客。 每个<entry>包含更多详细信息,包括每个博客的标题,描述,创建日期,最后更新日期和作者。 每个条目还包括一组提要链接,这些提要链接包含博客文章,博客模板和博客设置。

清单1中 ,每个博客都与一个唯一的标识符或博客ID相关联。 博客ID用于构造指向博客特定供稿的URL。 例如,要查找特定博客的帖子供稿,请使用<link rel='http://schemas.google.com/g/2005#post' ... />元素中指定的URL。 清单2显示了帖子提要的外观。

清单2. Blogger发布提要
<?xml version='1.0' encoding='UTF-8'?>
<?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?>
<feed xmlns='http://www.w3.org/2005/Atom' 
 xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' 
 xmlns:georss='http://www.georss.org/georss' 
 xmlns:thr='http://purl.org/syndication/thread/1.0'>
  <id>tag:blogger.com,1999:blog-12345BLOGIDHERE12345</id>
  <updated>2011-09-01T21:06:44.240-07:00</updated>
  <title type='text'>V Vaswani's Blog</title>
  <subtitle type='html'></subtitle>
  <link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' 
   href='http://vvaswani.blogspot.com/feeds/posts/default'/>
  <link rel='self' type='application/atom+xml' 
   href='http://www.blogger.com/feeds/12345BLOGIDHERE12345/posts/default'/>
  <link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml' 
   href='http://www.blogger.com/feeds/12345BLOGIDHERE12345/posts/default'/>
  <link rel='alternate' type='text/html' href='http://vvaswani.blogspot.com/'/>
  <author>
    <name>V Vaswani</name>
    <email>noreply@blogger.com</email>
  </author>
  <generator version='7.00' uri='http://www.blogger.com'>Blogger</generator>
  <openSearch:totalResults>3</openSearch:totalResults>
  <openSearch:startIndex>1</openSearch:startIndex>
  <openSearch:itemsPerPage>25</openSearch:itemsPerPage>
  <entry>
    <id>tag:blogger.com,1999:blog-12345BLOGIDHERE12345.post-
     12345POSTIDHERE12345</id>
    <published>2011-09-01T03:34:00.001-07:00</published>
    <updated>2011-09-01T21:06:44.258-07:00</updated>
    <title type='text'>My Third Post</title>
    <content type='html'>This is my third post
    <br /></content>
    <link rel='replies' type='application/atom+xml' 
     href='http://vvaswani.blogspot.com/feeds/12345POSTIDHERE12345/comments/default'
     title='Post Comments'/>
    <link rel='replies' type='text/html' 
     href='https://www.blogger.com/comment.g?
     blogID=12345BLOGIDHERE12345&postID=12345POSTIDHERE12345' 
     title='0 Comments'/>
    <link rel='edit' type='application/atom+xml' 
     href='http://www.blogger.com/feeds/12345BLOGIDHERE12345/posts/
     default/12345POSTIDHERE12345'/>
    <link rel='self' type='application/atom+xml' 
     href='http://www.blogger.com/feeds/12345BLOGIDHERE12345/posts/
     default/12345POSTIDHERE12345'/>
    <link rel='alternate' type='text/html' 
     href='http://vvaswani.blogspot.com/2011/09/my-third-d.html' 
     title='My Third Post'/>
    <author>
    <name>V Vaswani</name>
    <email>noreply@blogger.com</email>
    </author>
    <thr:total>0</thr:total>
  </entry>
  ...
</feed>

清单2揭示了帖子提要包含一组<entry>元素,并且每个元素都代表博客的单个帖子。 每个<entry>包括:

  • 帖子的标题,内容和发布日期。
  • 链接到帖子的公共URL,帖子编辑URL,评论供稿URL和评论供稿编辑URL。 这些供稿用于通过Blogger数据API查看和编辑帖子或其评论。

每个帖子还有一个唯一的标识符,称为帖子ID,位于条目的<id>元素中。 它是一个包含博客ID和帖子ID的复合字符串,格式为tag:blogger.com,1999:blog-BLOGID.post-POSTID 。 例如,在标识字符串tag:blogger.com,1999:blog-1234.post-6789 ,博客标识符为1234 ,帖子标识符为6789

检索博客和帖子

既然您知道如何通过API访问博客和发布供稿,请在PHP应用程序中尝试相同的操作。 要生成清单12中的提要,您首先要使用Google帐户手动登录Blogger。 要从PHP应用程序中检索和处理提要,需要以编程方式执行相同的身份验证任务。

手动执行身份验证是一个相当麻烦的任务,需要大量代码来解决在典型身份验证事务期间可能出现的各种情况。 幸运的是,Zend框架包括Zend_Gdata,这是一个PHP客户端库,专门为尝试将PHP应用程序与Google Data API集成的开发人员而设计。 Zend_Gdata提供了一个方便的,面向对象的接口,以谷歌数据API(见链接相关主题进行下载)。 它封装了包括身份验证在内的大多数常见任务,使您可以将精力集中在应用程序的核心功能上。

安装Zend的Gdata库后,请看清单3 。 它显示了如何处理清单1中的提要,并将其转换为列出Blogger上所有经过身份验证的用户的Weblog的网页。

清单3.列出博客
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Feed');

// set credentials for ClientLogin authentication
$user = "your-username@gmail.com";
$pass = "your-password";

try {
  // perform login 
  // initialize service object
  $client = Zend_Gdata_ClientLogin::getHttpClient(
    $user, $pass, 'blogger');
  $service = new Zend_Gdata($client);

  // get list of all blogs
  $query = new Zend_Gdata_Query('http://www.blogger.com/feeds/default/blogs');
  $feed = $service->getFeed($query);
} catch (Exception $e) {
  die('ERROR:' . $e->getMessage());  
}
?>
<html>
  <head></head>
  <body>
    <h2>Blogs</h2>
    <ul>
      <?php foreach ($feed as $entry): ?>      
      <li>
        <a href="<?php 
         echo $entry->getLink('alternate')->getHref(); ?>">
         <?php echo $entry->getTitle(); ?> 
        </a>          
      </li>
      <?php endforeach; ?>
    </ul>  
  </body>
</html>

清单3加载Zend类库并初始化Zend_Gdata服务类的实例。 Zend_Gdata使用Zend_Http_Client对象,该对象提供了必要的用户身份验证信息,并用于打开与Blogger服务的身份验证连接。 此类还用作与Blogger Data API进行所有后续交互的控制点。

打开经过身份验证的连接后,将使用getFeed()方法检索博客列表。 getFeed()接受Zend_Gdata_Query对象,该对象传递给博客列表供稿的URL。 对getFeed() API调用的响应是类似于清单1的XML提要,然后将其解析并转换为PHP对象。 提要中的条目表示为数组元素,从而可以:

  • 遍历提要
  • 检索单个博客名称和URL
  • 格式化它们以在Web浏览器中显示

图1显示了您可能看到的输出。

图1.显示用户博客的示例网页
列出用户博客的网页的屏幕截图

如前所述,Blogger服务中的每个博客和帖子都有一个唯一的标识符。 如果您具有博客的唯一标识符,则可以生成相应博客提要的URL,其中包含该博客中所有帖子的列表。 清单4显示了使用Zend_Gdata客户端库检索和处理此类博客供稿的过程。

清单4.列出博客文章
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Feed');

// set credentials for ClientLogin authentication
$user = "your-username@gmail.com";
$pass = "your-password";

try {
  // perform login 
  // initialize service object
  $client = Zend_Gdata_ClientLogin::getHttpClient(
    $user, $pass, 'blogger');
  $service = new Zend_Gdata($client);

  // get list of all posts in blog feed
  $query = new Zend_Gdata_Query(
   'http://www.blogger.com/feeds/YOUR-BLOG-ID-HERE/posts/default');
  $feed = $service->getFeed($query);
} catch (Exception $e) {
  die('ERROR:' . $e->getMessage());  
}
?>
<html>
  <head></head>
  <body>
    <h2>Posts</h2>
    <ul>
      <?php foreach ($feed as $entry): ?>      
      <li>
        <a href="<?php 
         echo $entry->getLink('alternate')->getHref(); ?>">
            <?php echo $entry->getTitle(); ?> 
        </a>          
      </li>
      <?php endforeach; ?>
    </ul>  
  </body>
</html>

清单3所示清单4首先初始化Zend库并创建一个经过身份验证的Zend_Gdata服务对象。 博客标识符用于构造博客提要的URL,该URL会转换为Zend_Gdata_Query对象并传递给getFeed()方法。 然后,以通常的方式解析和处理生成的提要,以生成指定博客中所有帖子的列表。 图2显示了输出示例。

图2.显示用户博客文章的网页
列出用户博客文章的网页的屏幕截图

您可以将清单3清单4组合在一起,以生成所有经过身份验证的用户博客和每个博客中的帖子的列表。 清单5显示了合并的代码。

清单5.列出博客和博客文章
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Feed');

// set credentials for ClientLogin authentication
$user = "your-username@gmail.com";
$pass = "your-password";

try {
  // perform login 
  // initialize service object
  $client = Zend_Gdata_ClientLogin::getHttpClient(
    $user, $pass, 'blogger');
  $service = new Zend_Gdata($client);

  // create array
  $data = array();
  
  // get list of all posts in all blog feeds
  $query1 = new Zend_Gdata_Query('http://www.blogger.com/feeds/default/blogs');
  $feed1 = $service->getFeed($query1);
  foreach ($feed1 as $entry1) {
    $arr = explode('-', (string)$entry1->getId());
    $id = $arr[2];
    $query2 = new Zend_Gdata_Query(
     'http://www.blogger.com/feeds/'.$id.'/posts/default');
    $feed2 = $service->getFeed($query2);
    $blogArray = array(
      'title' => (string)$entry1->getTitle(), 
      'uri' => (string)$entry1->getLink('alternate')->getHref(),
      'posts' => array()
    );
    foreach ($feed2 as $entry2) {
      $postArray = array(
        'title' => (string)$entry2->getTitle(), 
        'uri' => (string)$entry2->getLink('alternate')->getHref()
      );
      $blogArray['posts'][] = $postArray;
    }
    $data[] = $blogArray;
  }
} catch (Exception $e) {
  die('ERROR:' . $e->getMessage());  
}
?>
<html>
  <head></head>
  <body>
    <h2>Blogs and Posts</h2>
    <div id="results">
      <?php foreach ($data as $d): ?>      
      <ul>      
        <li><a href="<?php echo $d['uri']; ?>">
        <?php echo $d['title']; ?></a></li>
          <ul>
          <?php foreach ($d['posts'] as $p): ?>      
            <li><a href="<?php echo $p['uri']; ?>">
            <?php echo $p['title']; ?></a></li>
          <?php endforeach; ?>
          </ul>
      </ul>
      <?php endforeach; ?>
    </div>  
  </body>
</html>

清单5首先请求博客元供稿,并对其中的条目进行迭代以检索每个博客的唯一标识符。 然后,此标识符用于构造博客帖子供稿的URL,请求并对其进行处理以提取每个帖子的标题和URL。 所有这些信息都存储在一个嵌套数组中,如清单6所示

清单6.嵌套数组
Array
(
  [0] => Array
  (
    [title] => V Vaswani's Blog
    [uri] => http://***.blogspot.com/
    [posts] => Array
    (
      [0] => Array
      (
        [title] => My Fourth Post
        [uri] => http://***.blogspot.com/2011/09/my-fourth-post.html
      )

      [1] => Array
      (
        [title] => My Third Post
        [uri] => http://***.blogspot.com/2011/09/my-third-d.html
      )

      [2] => Array
      (
        [title] => My Second Post
        [uri] => http://***.blogspot.com/2011/08/my-second-post.html
      )

      [3] => Array
      (
        [title] => My First Post
        [uri] => http://***.blogspot.com/2008/02/testing.html
      )
    )
  )

  [1] => Array
  (
    [title] => V Vaswani's Second Blog
    [uri] => http://***.blogspot.com/
    [posts] => Array
    (
      [0] => Array
      (
        [title] => My First Post in my Second Blog
        [uri] => http://***.blogspot.com/2011/09/my-first-post-in-my-second-blog.html
      )
    )
  )
)

一旦数组完全生成,您就可以对其进行迭代并准备一个嵌套的博客及其帖子列表。 图3显示了输出示例。

图3.显示用户博客和博客文章的网页
网页的屏幕截图,列出了用户的博客和每个博客的博客文章

添加博客文章

除了允许帖子检索外,Blogger Data API还允许经过身份验证的用户以编程方式向博客添加新帖子。 创建一个新的Zend_Gdata_App_Entry对象,设置其标题和内容,然后将其发布到帖子提要中。 清单7显示了示例代码。

清单7.添加博客文章
<?php
if (isset($_POST['submit'])) {

  // load Zend Gdata libraries
  require_once 'Zend/Loader.php';
  Zend_Loader::loadClass('Zend_Gdata');
  Zend_Loader::loadClass('Zend_Gdata_Query');
  Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
  Zend_Loader::loadClass('Zend_Gdata_Feed');

  // set credentials for ClientLogin authentication
  $user = "your-username@gmail.com";
  $pass = "your-password";

  // set blog id
  $id = 'YOUR-BLOG-ID-HERE';

  try {
    // perform login 
    // initialize service object
    $client = Zend_Gdata_ClientLogin::getHttpClient(
      $user, $pass, 'blogger');
    $service = new Zend_Gdata($client);

    // create a new entry object
    // populate it with user input    
    $uri = 'http://www.blogger.com/feeds/' . $id . '/posts/default';
    $entry = $service->newEntry();
    $entry->title = $service->newTitle($_POST['title']);
    $entry->content = $service->newContent($_POST['body']);
    $entry->content->setType('text');

    // save entry to server
    // return unique id for new post
    $response = $service->insertEntry($entry, $uri);
    $arr = explode('-', $response->getId());
    $id = $arr[2];
    echo 'Successfully added post with ID: ' . $id;

  } catch (Exception $e) {
    die('ERROR:' . $e->getMessage());  
  }
}
?>
<html>
  <head></head>
  <body>
    <h2>Add New Post</h2>
    <form method="post">
      Title: <br/> <input type="text" name="title" 
       size="50" /> <br/>
      Body: <br/> <textarea name="body" cols="40" 
       rows="10"> </textarea> <br/>
      <input type="submit" name="submit" value="Post" />
    </form>
  </body>
</html>

清单7的代码中,一个简单的Web表单允许用户输入博客文章的标题和正文。 提交表单后,脚本将加载Zend类库并创建一个经过身份验证的服务对象。 然后,脚本使用服务对象的newEntry()方法创建一个新的条目对象,并使用newTitle()newContent()方法根据用户的输入设置博客文章的标题和内容。 设置insertEntry()这些属性后,将使用insertEntry()方法将新帖子保存到Google的服务器中。

图4显示了表单的示例。

图4.添加新博客文章的Web表单
该网络表单的屏幕截图,用于添加带有“标题”和“正文”字段的新博客帖子

insertEntry()方法的返回值是一个代表新创建帖子的条目。 现在,该条目包含帖子的唯一标识符,可以将其提取并显示在结果页面上。 保存后,新帖子将在公共博客中可见,并且还会显示在该博客的所有API供稿中。

编辑和删除博客文章

您还可以通过Blogger数据API删除或编辑现有帖子。 在这两种情况下,都必须将相应的DELETE或PUT请求传输到帖子的编辑URL(有关示例,请参见清单2 )。 只有经过身份验证的用户才能执行这两项操作。

清单8中的代码显示了假设您已经具有博客和帖子ID的情况,如何通过API删除现有博客帖子。

清单8.删除博客文章
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Feed');

// set credentials for ClientLogin authentication
$user = "your-username@gmail.com";
$pass = "your-password";

// set blog and post ids
$bid = 'YOUR-BLOG-ID-HERE';
$pid = 'YOUR-POST-ID-HERE';

try {
  // perform login 
  // initialize service object
  $client = Zend_Gdata_ClientLogin::getHttpClient(
    $user, $pass, 'blogger');
  $service = new Zend_Gdata($client);

  // set URI for entry to delete
  // obtain from <link rel=edit ... />
  $uri = 'http://www.blogger.com/feeds/' . $bid . '/posts/default/' . $pid;
  $service->delete($uri);
  echo 'Successfully deleted post with ID: ' . $pid;

} catch (Exception $e) {
  die('ERROR:' . $e->getMessage());  
}
?>

清单8使用服务对象的delete()方法删除指定的博客文章。 delete()方法接受帖子的编辑URL,并将DELETE请求发送到该URL。 删除后,博客帖子将从公共博客和引用该博客的所有API供稿源中消失。

要再次显示代码以通过API更新现有博客文章的代码,并再次假设您已经拥有博客和文章ID,请使用清单9中的代码。

清单9.更新博客文章
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Feed');

// set credentials for ClientLogin authentication
$user = "your-username@gmail.com";
$pass = "your-password";

// set blog and post ids
$bid = 'YOUR-BLOG-ID-HERE';
$pid = 'YOUR-POST-ID-HERE';

try {
  // perform login 
  // initialize service object
  $client = Zend_Gdata_ClientLogin::getHttpClient(
    $user, $pass, 'blogger');
  $service = new Zend_Gdata($client);

  // set URI for entry to update
  // obtain from <link rel=self ... />
  $uri = 'http://www.blogger.com/feeds/' . $bid . '/posts/default/' . $pid;

  // get the existing entry
  // set new values
  // save it back
  $response = $service->get($uri);
  $entry = new Zend_Gdata_App_Entry($response->getBody());
  $entry->title = $service->newTitle("New title");
  $entry->content = $service->newContent("New content");
  $entry->content->setType('text');
  $service->updateEntry($entry);
  echo 'Successfully updated post with ID: ' . $pid;

} catch (Exception $e) {
  die('ERROR:' . $e->getMessage());  
}
?>

通过API更新博客文章需要两个步骤。 首先,您需要检索现有的博客文章并将其转换为Zend_Gdata_App_Entry对象。 然后,您可以使用诸如newTitle()newContent()类的服务对象方法来更新条目,并使用updateEntry()方法将其保存回服务器。

类似于insertEntry()的方法,所述的返回值updateEntry()方法是代表后,包括其唯一标识符和内容的条目。 保存后,更新后的帖子将在公共博客和引用该博客的所有API供稿中可见。

处理评论

正如您可以添加,编辑和删除帖子一样,您也可以添加,编辑和删除帖子评论。 在清单2中 ,请注意,每个帖子条目都包含指向该帖子的提要的链接。 添加新评论就像在此评论提要中插入一个条目一样简单。

清单10显示了向帖子添加新评论的过程。

清单10.添加新评论
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Feed');

// set credentials for ClientLogin authentication
$user = "your-username@gmail.com";
$pass = "your-password";

// set blog and post ids
$bid = 'YOUR-BLOG-ID-HERE';
$pid = 'YOUR-POST-ID-HERE';

try {
  // perform login 
  // initialize service object
  $client = Zend_Gdata_ClientLogin::getHttpClient(
    $user, $pass, 'blogger');
  $service = new Zend_Gdata($client);

  // create a new entry object
  // populate it with user input    
  $uri = "http://www.blogger.com/feeds/$bid/$pid/comments/default";
  $entry = $service->newEntry();
  $entry->content = $service->newContent('This is a very interesting post.');
  $entry->content->setType('text');

  // save entry to server
  // return unique id for new comment
  $response = $service->insertEntry($entry, $uri);
  $arr = explode('/', $response->getEditLink()->href);
  $id = $arr[8];
  echo 'Successfully added comment with ID: ' . $id;

} catch (Exception $e) {
  die('ERROR:' . $e->getMessage());  
}
?>

添加新评论与添加新帖子几乎相同。 唯一的区别在于将请求发布到的URL(在本例中为评论提要URL)。 对insertEntry()方法的响应是一个表示新添加的注释的对象。 然后可以解析该对象以检索唯一的注释标识符,如果以后要删除注释,则需要此标识符。

假设您具有注释标识符,则可以使用清单11中的代码通过delete()方法以编程方式删除注释。

清单11.删除评论
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Feed');

// set credentials for ClientLogin authentication
$user = "your-username@gmail.com";
$pass = "your-password";

// set blog, post and comment ids
$bid = 'YOUR-BLOG-ID-HERE';
$pid = 'YOUR-POST-ID-HERE';
$cid = 'YOUR-COMMENT-ID-HERE';

try {
  // perform login 
  // initialize service object
  $client = Zend_Gdata_ClientLogin::getHttpClient(
    $user, $pass, 'blogger');
  $service = new Zend_Gdata($client);

  // set URI for entry to delete
  // obtain from <link rel=edit ... />
  $uri = "http://www.blogger.com/feeds/$bid/$pid/comments/default/$cid";
  $service->delete($uri);
  echo 'Successfully deleted comment with ID: ' . $cid;

} catch (Exception $e) {
  die('ERROR:' . $e->getMessage());  
}
?>

您还可以使用相同的评论提要URL来检索帖子的所有评论的列表,如清单12所示

清单12.清单注释
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Feed');

// set credentials for ClientLogin authentication
$user = "your-username@gmail.com";
$pass = "your-password";

// set blog and post ids
$bid = 'YOUR-BLOG-ID-HERE';
$pid = 'YOUR-POST-ID-HERE';

try {
  // perform login 
  // initialize service object
  $client = Zend_Gdata_ClientLogin::getHttpClient(
    $user, $pass, 'blogger');
  $service = new Zend_Gdata($client);

  // get list of all comments for post
  $uri = "http://www.blogger.com/feeds/$bid/$pid/comments/default/";
  $query = new Zend_Gdata_Query($uri);
  $feed = $service->getFeed($query);
} catch (Exception $e) {
  die('ERROR:' . $e->getMessage());  
}
?>
<html>
  <head></head>
  <body>
    <h2>Comments</h2>
    <div id="results">
      <ul>
      <?php foreach ($feed as $entry): ?>      
        <?php $author = $entry->getAuthor(); ?>
        <li><?php echo $entry->getTitle(); ?> 
         - <?php echo $author[0]->getName(); ?> <br/>
        <?php echo date('d M Y H:i', strtotime($entry->getUpdated())); ?>
        </li>          
      <?php endforeach; ?>
    </ul>  
  </body>
</html>

示例应用程序:内容管理系统

让我们通过构建一个简单的真实应用程序将Blogger Data API的强大功能付诸实践。 该示例应用程序是一个基于Web的内容管理器,它使用户可以查看其现有博客文章,添加新文章以及编辑或删除现有文章。 编辑是通过基于浏览器的WYSIWYG编辑器执行的,并通过Blogger Data API传输到Blogger。

首先,在开发服务器上下载并安装TinyMCE JavaScript编辑器(请参阅参考资料中的链接)。 创建一个包含清单13中所示代码的脚本。

清单13.管理博客内容
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Feed');

// set credentials for ClientLogin authentication
$user = "your-username@gmail.com";
$pass = "your-password";

// set blog id
$bid = 'YOUR-BLOG-ID-HERE';

try {
  // perform login 
  // initialize service object
  $client = Zend_Gdata_ClientLogin::getHttpClient(
    $user, $pass, 'blogger');
  $service = new Zend_Gdata($client);

  // for add and edit operations
  if (isset($_POST['submit'])) {
    // if post id present
    // update post with new content
    if (isset($_POST['pid'])) {      
      $arr = explode('-', $_GET['pid']);
      $pid = $arr[2];
      $uri = 'http://www.blogger.com/feeds/' . $bid . '/posts/default/' . $pid;
      $response = $service->get($uri);
      $entry = new Zend_Gdata_App_Entry($response->getBody());
      $entry->title = $service->newTitle($_POST['title']);
      $entry->content = $service->newContent($_POST['body']);
      $entry->content->setType('text');
      $service->updateEntry($entry);
      echo 'Successfully updated post with ID: ' . $pid;    
    } else {
      // if post id not present
      // create a new post
      // populate it with user input    
      $uri = 'http://www.blogger.com/feeds/' . $bid . '/posts/default';
      $entry = $service->newEntry();
      $entry->title = $service->newTitle($_POST['title']);
      $entry->content = $service->newContent($_POST['body']);
      $entry->content->setType('text');
      $response = $service->insertEntry($entry, $uri);
      $arr = explode('-', $response->getId());
      $id = $arr[2];
      echo 'Successfully added post with ID: ' . $id;  
    }
  }

  // for edit and delete operations
  if (isset($_GET['op'])) {
    // generate post URL
    $arr = explode('-', $_GET['pid']);
    $pid = $arr[2];
    $uri = 'http://www.blogger.com/feeds/' . $bid . '/posts/default/' . $pid;
    switch($_GET['op']) {
      case 'delete':
        // delete post
        $service->delete($uri);
        echo 'Successfully deleted post with ID: ' . $pid;      
        break;
      case 'edit':
        // retrieve post for display in edit form
        $response = $service->get($uri);
        $entry = new Zend_Gdata_App_Entry($response->getBody());
    }
  }
  
  // get list of all posts in blog feed
  $query = new Zend_Gdata_Query(
   'http://www.blogger.com/feeds/'.$bid.'/posts/default');
  $feed = $service->getFeed($query);
} catch (Exception $e) {
  die('ERROR:' . $e->getMessage());  
}
?>
<html>
  <head>
    <script type="text/javascript" 
     src="tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
    <script type="text/javascript">
    tinyMCE.init({
            mode : "textareas",
            theme : "advanced",
            theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,
             justifycenter,justifyright,|,code,preview,|,forecolor,backcolor,|,sub,sup,
             |,fontsizeselect",
            theme_advanced_buttons2 : "cut,copy,paste,|,bullist,numlist,|,outdent,indent,
             |,undo,redo,|,link,unlink,anchor,image,|,removeformat",
            theme_advanced_buttons3 : "",      
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : true
    });

    </script>
  </head>
  <body>
    <h2>View Posts</h2>
    <ul>
    <?php foreach ($feed as $e): ?>  
      <li><?php echo $e->getTitle(); ?> <br/>
      <a href="<?php 
      echo $e->getLink('alternate')->getHref(); ?>">View</a> 
       | <a href="?op=edit&pid=<?php echo $e->getId(); ?>">Edit</a>
       | <a href="?op=delete&pid=<?php echo $e->getId(); ?>">Delete
       </a>
      </li>
    <?php endforeach; ?>
    </ul>
    <a href="<?php echo $_SERVER['PHP_SELF']; ?>">
     Add a new post</a>
    <?php if (isset($_GET['op']) && $_GET['op'] == 'edit'): ?>
    <h2>Edit Post</h2>
    <form method="post">
      Title: <br/> <input type="text" name="title" size="50" 
       value="<?php echo $entry->title; ?>" /> <br/>
      Body: <br/> <textarea name="body" cols="40" 
       rows="10"><?php echo $entry->content; ?></textarea> <br/>
      <input type="hidden" name="pid" 
       value="<?php echo $entry->id; ?>" />
      <input type="submit" name="submit" value="Post" />
    </form>
    <?php else: ?>
    <h2>Add New Post</h2>
    <form method="post">
      Title: <br/> <input type="text" name="title" 
       size="50" /> <br/>
      Body: <br/> <textarea name="body" cols="40" 
       rows="10"> </textarea> <br/>
      <input type="submit" name="submit" value="Post" />
    </form>
    <?php endif; ?>
  </body>
</html>

上面的代码可能看起来很复杂,但这只是围绕您已经看到的代码的几个条件语句。 如下将其分解可能会有所帮助。

  • 该脚本首先加载Zend类库并设置身份验证凭据。 它还定义了博客ID。 所有后续操作将仅在指定的博客上进行。
  • 假设不存在请求参数,该脚本将连接到Blogger API并请求指定博客中所有帖子的列表。 然后,它处理生成的提要,并将帖子列表显示为HTML列表。

    每个帖子都有三个链接:“ View ,“ Edit ”或“ Delete ”。 “ View链接指定帖子的公共URL。 “ Edit和“ Delete链接只是再次调用脚本,将选定的帖子ID作为GET请求参数传递给该脚本。

  • 在生成当前帖子列表之后,脚本还将生成一个Web表单供用户添加新帖子。 该表单包含一个单行文本输入字段(用于帖子标题)和一个多行文本区域(用于帖子正文)。

    TinyMCE编辑器也会在页面加载时初始化,它会自动处理将文本区域转换为带有格式和超链接控件的WYSIWYG文本编辑字段。

  • 接下来会发生什么取决于用户选择哪种操作。
    如果用户选择... 然后...
    添加新帖子 将内容输入到Web表单并提交后,脚本将使用newEntry()方法创建一个新的条目对象,并使用提交的输入来填充它,然后使用insertEntry()方法将其保存到博客中。
    删除现有帖子 从请求URL中检索所选帖子的ID,并使用博客ID和帖子ID构造帖子供稿URL。 然后使用服务对象的delete()方法删除该帖子。
    编辑现有帖子 从请求URL中检索所选帖子的ID,并使用博客ID和帖子ID构造帖子供稿URL。 然后使用服务对象的get()方法检索该帖子。 帖子的内容与包含唯一帖子ID的隐藏字段一起用于预填充Web表单进行编辑。

    用户对内容进行更改并重新提交表单后,隐藏的帖子ID用于使用updateEntry()方法标识和更新现有帖子。

为了简单起见,此脚本不包含任何输入验证。 在生产环境中,您需要添加验证以确保从用户那里收集的数据的完整性和有效性。

图5显示了示例内容管理系统。

图5.博客内容管理界面
博客内容管理界面的屏幕截图

结论

在本文中,您学习了如何使用Blogger数据API和Zend Gdata客户端库将Blogger博客文章直接集成到PHP应用程序中。 本文提供了Blogger供稿格式的简介。 您还学习了如何:

  • 检索博客,帖子和评论
  • 添加,编辑和删除帖子
  • 查看,添加和删除评论

Blogger API提供了一种复杂的,独立于格式的机制,可以将公共博客内容集成到任何Web应用程序中。 这非常适合混搭,也可以为Blogger构建您自己的自定义界面。 尝试一下,看看你能做什么。


翻译自: https://www.ibm.com/developerworks/xml/library/x-blogger/index.html

blogger

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值