Skip to content

Instantly share code, notes, and snippets.

@KanDai
Last active February 22, 2023 05:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KanDai/0467e30278b6686f190fa14fec1348c0 to your computer and use it in GitHub Desktop.
Save KanDai/0467e30278b6686f190fa14fec1348c0 to your computer and use it in GitHub Desktop.
WordPressの記事データをmicroCMSにPOSTする
<?php
// 移行記事のxmlファイルを指定
$xml = "./foo.xml";
// microCMSの画像用CDNのURLとパス
$imgBasePath = 'https://images.microcms-assets.io/bar/';
// xmlを読み込み
$xmlData = simplexml_load_file($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
$url = 'microCMSのAPIのエンドポイント';
$headers = array(
'Content-Type: application/json',
'X-WRITE-API-KEY: 取得したAPI-KEY'
);
foreach ($xmlData->channel->item as $entry) {
// カテゴリの設定
$cateArray = [];
$categories = json_decode(json_encode($entry->category), true);
foreach ($categories as $category) {
if (is_array($category)) continue;
switch($category) {
case 'お知らせ01':
$cateArray[] = 'topics01';
break;
case 'お知らせ02':
$cateArray[] = 'topics02';
break;
case 'お知らせ03':
$cateArray[] = 'topics03';
break;
}
}
// コンテンツ取得
$contents = trim(strval($entry->children('content', true)->encoded));
// 画像を使っている部分を正規表現で抽出
preg_match_all('/src="https:\/\/foober\.com\/wp-content\/uploads\/(.*)(png|jpg|jpeg|gif)/i', $contents, $matches);
// 置き換え用の配列を作成
$pattern = [];
$replace = [];
foreach ($matches[0] as $key => $match) {
$pattern[] = '/' . preg_replace('/\//', '\/', $match) . '/';
$pathArray = explode('/', $match);
$paths = array_reverse($pathArray);
$replace[] = 'src="' . $imgBasePath . "{$paths[2]}_{$paths[1]}_{$paths[0]}";
}
// 置き換え実行
$html_content = preg_replace($pattern, $replace, $contents);
// 送信用のデータ作成
$data = [
'id' => '000' . strval($entry->children('wp', true)->post_id),
'title' => trim(strval($entry->title)),
'category' => array_unique($cateArray),
'html_contents' => $html_content,
'is_html' => true,
'is_migration' => true
];
// curlでPOSTする
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$html = curl_exec($ch);
// curlでエラー
if(curl_errno($ch)){
$CURLERR .= 'curl_errno:' . curl_errno($ch) . "\n";
$CURLERR .= 'curl_error:' . curl_error($ch) . "\n";
$CURLERR .= '▼curl_getinfo' . "\n";
foreach(curl_getinfo($ch) as $key => $val){
$CURLERR .= '■' . $key . ':' . $val . "\n";
}
echo nl2br($CURLERR);
}
curl_close($ch);
// 結果の表示
echo $data['id'] . ':' . $html . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment