Skip to content

Instantly share code, notes, and snippets.

@cmbuckley
Last active May 13, 2018 00:15
Embed
What would you like to do?
Emit WordPress comments as YML
<?php
$file = $argv[1];
$header = null;
$spec = array(
'_id' => function ($data) {
return intval($data['comment_ID']);
},
'name' => 'comment_author',
'email' => function ($data) {
return (empty($data['comment_author_email']) ? '' : md5($data['comment_author_email']));
},
'comment' => function ($data) {
return trim($data['comment_content']);
},
'date' => function ($data) {
return strtotime($data['comment_date_gmt'] . ' UTC');
},
);
if ($fh = fopen($file, 'r')) {
while ($data = fgetcsv($fh)) {
if ($header) {
// convert data to YAML
$comment = array_combine($header, array_slice($data, 0, count($header)));
$yaml = substr(yaml_emit(map($comment, $spec), YAML_UTF8_ENCODING), 4, -4);
// create directory
$dir = $argv[3] . '/' . slug($comment['comment_post_ID'], $argv[2]);
echo "Creating directory $dir\n";
if (!file_exists($dir)) { mkdir($dir); }
echo "Creating comment $dir/${comment['comment_ID']}.yml\n\n";
file_put_contents("$dir/" . $comment['comment_ID'] . '.yml', $yaml);
}
else {
$header = $data;
}
}
}
function map($data, $spec) {
$return = array();
foreach ($spec as $field => $value) {
$return[$field] = (is_callable($value) ? $value($data) : $data[$value]);
}
return array_filter($return);
}
function slug($id, $site, $pattern = '~^/blog/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[^/]+)/$~') {
echo "Getting URL for $site?p=$id\n";
$ch = curl_init($site . "?p=$id");
curl_exec($ch);
$url = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
curl_close($ch);
echo "Got URL $url\n";
if (preg_match($pattern, str_replace($site, '', $url), $matches)) {
return $matches['year'] . '-' . $matches['month'] . '-' . $matches['day'] . '-' . $matches['slug'];
}
}
@cmbuckley
Copy link
Author

Takes a CSV as created by WordPress Comments Import & Export and outputs into separate YAML files to match Pull Requests created by Staticman.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment