본문 바로가기

Story/php

metaWeblog 를 이용하여 블로그(blog)에 글을 등록해보자

반응형

MetaWeblog API 란

The MetaWeblog API is an application programming interface created by software developer Dave Winer that enables weblog entries to be written, edited, and deleted using web services.

The API is implemented as an XML-RPC web service with three methods whose names describe their function: metaweblog.newPost(), metaweblog.getPost() and metaweblog.editPost(). These methods take arguments that specify the blog author's username and password along with information related to an individual weblog entry.

The impetus for the creation of the API in 2002 was perceived limitations of the Blogger API, which serves the same purpose. Another weblog publishing API, the Atom Publishing Protocol became an IETF Internet standard (RFC 5023) in October 2007.

Many blog software applications and content management systems support the MetaWeblog API, as do numerous desktop clients. As of June 2013, the +1000 websites hosted on AgileSite's CMS platform utilize MetaWeblog API. AgileSite partnered with Blogpress App for iPad / iPhone mobile support. The companies utilize the API to allow for easy and robust integration.


MetaWeblog API 는 블로그에 웹서비스를 사용하여 글을 읽기,등록,수정,삭제 할 수 있도록 하는 api 를 표준화한 것입니다.

xml-rpc

출처 : http://en.wikipedia.org/wiki/MetaWeblog


MetaWeblog API 참조

MetaWeblogAPI metaWeblog.newPost 메서드는 블로그에 새 항목을 게시합니다.

MetaWeblogAPI metaWeblog.editPost 메서드는 블로그의 기존 항목을 편집합니다.

MetaWeblogAPI metaWeblog.getPost 메서드는 블로그에서 특정 항목을 반환합니다.

MetaWeblogAPI metaWeblog.getCategories 메서드는 블로그에서 사용된 범주의 목록을 반환합니다.

MetaWeblogAPI metaWeblog.getRecentPosts 메서드는 가장 최근의 초안 게시물과 초안이 아닌 게시물을 게시 날짜 기준 내림차순으로 반환합니다.

MetaWeblogAPI blogger.deletePost 메서드는 블로그에서 게시물을 삭제합니다.

MetaWeblogAPI blogger.getUsersBlogs 메서드는 사용자의 스페이스에 대한 정보를 반환합니다.

MetaWeblogAPI blogger.getUserInfo 메서드는 이름, 전자 메일 주소, 사용자 ID와 같은 기본 사용자 정보를 반환합니다.

MetaWeblog API 오류에서는 Windows Live Spaces가 오류를 반환하도록 만드는 HTTP 작업 및 XML-RPC 작업에 대한 정보를 제공합니다.

출처 : http://msdn.microsoft.com/ko-kr/library/bb259697.aspx


여기서는 티스토리를 기준으로 예를 작성해보았다.

한글에 대한 처리는 모두 utf-8 로 해야 한다. 그렇지 않으면 오류가 생기고 동작하지 않는다.
등록,수정,삭제를 function 으로 정리해보자.
우선 blog api 를 사용하기 위해 key 값도 확인해 두자.

$_blogapi['url'] = "http://사용자임의주소.tistory.com/api";
$_blogapi['key'] = "관리자페이지에서 받은 key값";
$_blogapi['id'] = "블로그 로그인 아이디";
$_blogapi['pwd'] = "블로그 로그인 패스워드";
 

글 등록 newPost() metaWeblog.newMediaObject

function newPost($title, $description,$categories="",$tags="",$publish = true,$files=""){
	global $_blogapi;

	$client = new xmlrpc_client($_blogapi['url']); 

	$title = mb_convert_encoding($title,"UTF-8","ASCII,JIS,UTF-8,EUC-KR,SJIS");
	$description = mb_convert_encoding($description,"UTF-8","ASCII,JIS,UTF-8,EUC-KR,SJIS");
	$categories = mb_convert_encoding($categories,"UTF-8","ASCII,JIS,UTF-8,EUC-KR,SJIS");
	$tags = mb_convert_encoding($tags,"UTF-8","ASCII,JIS,UTF-8,EUC-KR,SJIS");
	$files['name'] = mb_convert_encoding($files['name'],"UTF-8","ASCII,JIS,UTF-8,EUC-KR,SJIS");

	/* 본문에 포함이 안되면 파일첨부가 안됨. */
	if( $files['name'] && $files['type'] && $files['bits'] ){

		$f = new xmlrpcmsg("metaWeblog.newMediaObject",
			array(
				new xmlrpcval($_blogapi['key'], "string"), // blogid.(블로그아이디)
				new xmlrpcval($_blogapi['id'], "string"), // user ID. (아이디)
				new xmlrpcval($_blogapi['pwd'], "string"), // password (비밀번호)
				new xmlrpcval(
					array(
						'name' => new xmlrpcval($files['name'], "string"),
						'type' => new xmlrpcval($files['type'], "string"),
						'bits' => new xmlrpcval($files['bits'], "base64"), //파일 바이너리 값
					), "struct")
			)
		);
		$f->request_charset_encoding = 'UTF-8';
		$tempResponse = $client->send($f);
		$uploadFileName = $tempResponse->val->me['struct']['url']->me['string'];

		$description .= "<img src='{$uploadFileName}' />";
	}

	$struct = array( 
		'title' => new xmlrpcval($title, "string"),
		'description' => new xmlrpcval($description, "string")
		,'categories' => new xmlrpcval(array(new xmlrpcval($categories,"string")), "array")
		,'mt_keywords' => new xmlrpcval($tags, "string") // naver 는 tags

	);

	$f = new xmlrpcmsg("metaWeblog.newPost",
		array(
			new xmlrpcval($_blogapi['key'], "string"), // blogid.(블로그아이디)
			new xmlrpcval($_blogapi['id'], "string"), // user ID. (아이디)
			new xmlrpcval($_blogapi['pwd'], "string"), // password (비밀번호)
			new xmlrpcval($struct , "struct"),
			new xmlrpcval($publish, "boolean") //publish... true는 공개, false는 비공개가 된다.
		)
	);

	$f->request_charset_encoding = 'UTF-8';

	return $response = $client->send($f); 
}
글 수정 editPost() metaWeblog.editPost
function editPost($postid,$title, $description,$categories="",$tags="",$publish = true,$files=""){
	global $_blogapi;

	$client = new xmlrpc_client($_blogapi['url']); 

	$title = mb_convert_encoding($title,"UTF-8","ASCII,JIS,UTF-8,EUC-KR,SJIS");
	$description = mb_convert_encoding($description,"UTF-8","ASCII,JIS,UTF-8,EUC-KR,SJIS");
	$categories = mb_convert_encoding($categories,"UTF-8","ASCII,JIS,UTF-8,EUC-KR,SJIS");
	$tags = mb_convert_encoding($tags,"UTF-8","ASCII,JIS,UTF-8,EUC-KR,SJIS");
	$files['name'] = mb_convert_encoding($files['name'],"UTF-8","ASCII,JIS,UTF-8,EUC-KR,SJIS");


	/* 본문에 포함이 안되면 파일첨부가 안됨. */
	if( $files['name'] && $files['type'] && $files['bits'] ){

		$f = new xmlrpcmsg("metaWeblog.newMediaObject",
			array(
				new xmlrpcval($_blogapi['key'], "string"), // blogid.(블로그아이디)
				new xmlrpcval($_blogapi['id'], "string"), // user ID. (아이디)
				new xmlrpcval($_blogapi['pwd'], "string"), // password (비밀번호)
				new xmlrpcval(
					array(
						'name' => new xmlrpcval($files['name'], "string"),
						'type' => new xmlrpcval($files['type'], "string"),
						'bits' => new xmlrpcval($files['bits'], "base64"), //파일 바이너리 값
					), "struct")
			)
		);
		$f->request_charset_encoding = 'UTF-8';
		$tempResponse = $client->send($f);
		$uploadFileName = $tempResponse->val->me['struct']['url']->me['string'];

		$description .= "<img src='{$uploadFileName}' />";
	}

	$struct = array( 
		'title' => new xmlrpcval($title, "string"),
		'description' => new xmlrpcval($description, "string")
		,'categories' => new xmlrpcval(array(new xmlrpcval($categories,"string")), "array")
		,'mt_keywords' => new xmlrpcval($tags, "string")
	);


	$f = new xmlrpcmsg("metaWeblog.editPost",
		array(
			new xmlrpcval($postid, "string"), // postid.
			new xmlrpcval($_blogapi['id'], "string"), // user ID. (아이디)
			new xmlrpcval($_blogapi['pwd'], "string"), // password (비밀번호)
			new xmlrpcval($struct , "struct"),
			new xmlrpcval($publish, "boolean") //publish... true는 공개, false는 비공개가 된다.
		)
	);

	$f->request_charset_encoding = 'UTF-8';

	return $response = $client->send($f);
}
글 삭제  deletePost() blogger.deletePost
function deletePost($postid){
	global $_blogapi;

	$publish = false;	

	$client = new xmlrpc_client($_blogapi['url']); 

	$f = new xmlrpcmsg("blogger.deletePost",
		array(
			new xmlrpcval($_blogapi['key'], "string"), // blogid.
			new xmlrpcval($postid, "string"), // postid
			new xmlrpcval($_blogapi['id'], "string"), // user ID. (아이디)
			new xmlrpcval($_blogapi['pwd'], "string"), // password (비밀번호)
			new xmlrpcval($publish, "boolean") //publish... true는 공개, false는 비공개가 된다.
		)
	);

	return $response = $client->send($f); 
}
첨부파일이 있다면 다음과 같이 정리한다. (이미지일경우만 테스트해봤는대 본문에 포함이 되지 않으면 저장이 되지 않는다.)
$tempFile = $_FILES['upload']['tmp_name'];
$fileName = $_FILES['upload']['name'];
$fileType = $_FILES['upload']['type'];


// 파일 바이너리 데이터 가져오기
$fp=fopen($tempFile, "rb");
if (!$fp) return null; // file open failure !!
while( !feof($fp)){
	$filedescription .= fread( $fp, 1024); // 1024 is the server compatible buffer size
	flush();
	@ob_flush();
}
fclose($fp);

$arr_file = array(
	"name"=>$fileName,
	"type"=>$fileType,
	"bits"=>$filedescription
);
사용예
$return = newPost('안녕하세요', 'API로 보낸글 입니다.','카테고리명','태그1,태그2',true,$arr_file); // 카테고리명은 실제 존재하는 카테고리와 이름이 동일해야 한다.
$postid = $return->val->me['string'];

$return = editPost($postid,'두번째안녕하세요', 'API로 보낸글 입니다.','카테고리명','태그1,태그2',true,$arr_file);

$return = deletePost($postid);

반응형