Skip to content

Instantly share code, notes, and snippets.

@felipeelia
Last active September 15, 2019 19:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipeelia/69940c40e5575a1d347ae13cf1cd44e9 to your computer and use it in GitHub Desktop.
Save felipeelia/69940c40e5575a1d347ae13cf1cd44e9 to your computer and use it in GitHub Desktop.
Given a WP REST API content list route, fetches all IDs, URLs, and Titles into a CSV file.
<?php
/**
* Usage example: `php -f fetch-from-wp-rest-api.php https://wordpress.org/support/wp-json/wp/v2/articles helphub-list`
*/
$first_page = file_get_contents( $argv[1] . '?per_page=100' );
$first_page_headers = parse_headers( $http_response_header );
$content = json_decode( $first_page, true );
for ( $i = 2; $i < $first_page_headers['X-WP-TotalPages']; $i++ ) {
$page = file_get_contents( $argv[1] . '?per_page=100&page=' . $i );
$page = json_decode( $page, true );
$content = array_merge( $content, $page );
}
$csv_lines = [
implode( ',', [ 'ID', 'URL', 'Title' ] ),
];
foreach ( $content as $post ) {
$csv_lines[] = implode(
',',
[ $post['id'], $post['link'], $post['title']['rendered'] ]
);
}
if ( ! empty( $argv[2] ) ) {
$filename = $argv[2] . '.csv';
} else {
$filename = date( 'Y-m-d-H-i-s' ) . '.csv';
}
file_put_contents( $filename, implode( "\n", $csv_lines ) );
echo "Done.\n";
function parse_headers( $headers ) {
$head = array();
foreach ( $headers as $k => $v ) {
$t = explode( ':', $v, 2 );
if ( isset( $t[1] ) ) {
$head[ trim( $t[0] ) ] = trim( $t[1] );
} else {
$head[] = $v;
if ( preg_match( '#HTTP/[0-9\.]+\s+([0-9]+)#', $v, $out ) ) {
$head['reponse_code'] = intval( $out[1] );
}
}
}
return $head;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment