Created
March 1, 2017 10:59
-
-
Save kasparsd/06c8aa04df48bceceb468d19d80b724a to your computer and use it in GitHub Desktop.
Extract attachment URLs from WordPress WXR export files
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 | |
| // Get a list of all WRX export files | |
| $files = glob( 'wrx-export/*.xml' ); | |
| // Remove invalid XML attributes and values which prevent SimpleXML from parsing the file | |
| // This shouldn't be necessary, if the exported creates a valid XML file. | |
| $replace = array( | |
| 'ü' => '', | |
| '…' => '', | |
| '<";' => '-";', | |
| ); | |
| $invalid = ''; | |
| foreach ( $files as $file_no => $xml_file ) { | |
| $attachments = ''; | |
| $xml = file_get_contents( $xml_file ); | |
| $filaname_save = sprintf( 'wrx-files/%d.txt', $file_no ); | |
| if ( file_exists( $filaname_save ) ) { | |
| continue; | |
| } | |
| // The Photon ?quality=100&strip=into thing makes this invalid XML | |
| $xml = preg_replace( '#&(?=[a-z_0-9]+=)#', '&', $xml ); | |
| $xml = str_replace( array_keys( $replace ), array_values( $replace ), $xml ); | |
| $xml = simplexml_load_string( $xml, 'SimpleXMLElement' ); | |
| if ( ! $xml ) { | |
| die( sprintf( 'Error at %s.', $xml_file ) ); | |
| } | |
| $ns = $xml->getNamespaces( true ); | |
| foreach ( $xml->channel->item as $post ) { | |
| $wp_data = $post->children( $ns['wp'] ); | |
| if ( isset( $wp_data->attachment_url ) && ! empty( $wp_data->attachment_url ) ) { | |
| $image_url = strtok( $wp_data->attachment_url, '?' ); | |
| // Mark URLs from other domains as "invalid" for further inspection | |
| if ( false !== strstr( $image_url, 'example.files.wordpress.com' ) ) { | |
| $attachments .= $image_url . "\n"; | |
| } else { | |
| $invalid .= $image_url . "\n"; | |
| } | |
| } | |
| } | |
| file_put_contents( $filaname_save, $attachments ); | |
| } | |
| file_put_contents( 'wrx-files-invalid.txt', $invalid ); | |
| echo "Done!"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment