Skip to content

Instantly share code, notes, and snippets.

@PatelUtkarsh
Created July 24, 2024 04:27
Show Gist options
  • Save PatelUtkarsh/6484663ca5db16b609932471f3ece365 to your computer and use it in GitHub Desktop.
Save PatelUtkarsh/6484663ca5db16b609932471f3ece365 to your computer and use it in GitHub Desktop.
To parse block names and counts from a JSON export from phpMyAdmin. Must export 'post_content' column.
<?php
// Function to extract block names from post content
function extractBlockNames($content) {
$blockNames = [];
$pattern = '/<!-- wp:([\w\/-]+)/';
preg_match_all($pattern, $content, $matches);
if (!empty($matches[1])) {
$blockNames = $matches[1];
}
return $blockNames;
}
// Read the JSON file
$jsonFile = 'wp_posts.json';
$jsonContent = file_get_contents($jsonFile);
// Parse JSON content
$data = json_decode($jsonContent, true);
// Initialize an array to store block names and their counts
$blockCounts = [];
// Loop through the data array
foreach ($data as $item) {
if (isset($item['data'])) {
foreach ($item['data'] as $post) {
if (isset($post['post_content'])) {
$blockNames = extractBlockNames($post['post_content']);
foreach ($blockNames as $blockName) {
if (!isset($blockCounts[$blockName])) {
$blockCounts[$blockName] = 1;
} else {
$blockCounts[$blockName]++;
}
}
}
}
}
}
// Sort the block counts by block name
asort($blockCounts);
// Output the results
echo "WordPress Block Names and Counts:\n";
foreach ($blockCounts as $blockName => $count) {
echo "- " . $blockName . ": " . $count . "\n";
}
// Output total unique blocks and total block count
echo "\nTotal Unique Blocks: " . count($blockCounts) . "\n";
echo "Total Block Count: " . array_sum($blockCounts) . "\n";
@PatelUtkarsh
Copy link
Author

Usage

php -d memory_limit=2G parse_blocks.php

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