Last active
September 15, 2019 19:15
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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