5

我在让 PHP 的 Blogger API 工作时遇到问题。

我需要的是能够将新的博文发布到我的博客帐户。我使用的代码取自此处的 Google API 页面: http ://code.google.com/intl/nl/apis/blogger/docs/1.0/developers_guide_php.html

这是我的代码:

<?
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');

$user = 'name@example.com';
$pass = 'password';
$service = 'blogger';

$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service, null,
        Zend_Gdata_ClientLogin::DEFAULT_SOURCE, null, null, 
        Zend_Gdata_ClientLogin::CLIENTLOGIN_URI, 'GOOGLE');
$gdClient = new Zend_Gdata($client); 

$blogID = '7973737751295446679';

function createPublishedPost($title='Hello, world!', $content='I am blogging on the internet.')
{
  $uri = 'http://www.blogger.com/feeds/' . $blogID . '/posts/default';
  $entry = $gdClient->newEntry();
  $entry->title = $gdClient->newTitle($title);
  $entry->content = $gdClient->newContent($content);
  $entry->content->setType('text');

  $createdPost = $gdClient->insertEntry($entry, $uri);
  $idText = split('-', $createdPost->id->text);
  $newPostID = $idText[2]; 

  return $newPostID; 
}

createPublishedPost();
?>

我得到的错误是“致命错误:在第 21 行调用 C:\xampp\htdocs\HelloWorld\blogger2.php 中的非对象上的成员函数 newEntry()”

谁能帮助我或给我一个工作代码示例,说明如何使用 PHP 向博主发帖?

4

2 回答 2

6

您的$gdClient变量在函数之外被激活createPublishedPost

$gdClient = new Zend_Gdata($client); 

在函数内部,在函数外部定义的变量默认不存在。
关于这一点,您可以查看手册的变量范围页面。

这意味着$gdClient函数内部不存在;因此,它是null;所以,不是一个对象——它解释了你得到的错误信息。


要自己检查,您可以使用

var_dump($gdClient);

在函数的开头:它会让你看到它是什么类型的数据;如果它不是您愿意使用的类的实例,那不是一个好兆头;-)


您可能想要:

  • 将该变量作为参数传递给createPublishedPost函数
  • 或将其声明为global函数内部(因此函数可以“看到”外部声明的变量)

The first solution is probably the cleanest one, I think ;-)


As a sidenote, you might want to configure your error_reporting level (see also), so you get an E_NOTICE when you are using a variable that is not declared -- in this case, you should have gotten one, for instance ;-)
You might also want to enable display_errors, on your development machine, if it's not already on -- seems to be, as you got the Fatal error message

It might seem a bit annoying at the beginning, but, once you get used to it, it is really great : allow to detect that kind of stuff a lot quicker ;-)
And it also helps detect typos in variable names ^^
And it makes you code way cleaner !

于 2009-08-16T17:19:43.753 回答
1

Moving the $gdClient to the function body fixed something, but you also have to move the $blogID into the function body.

于 2011-04-12T22:45:41.667 回答