Copying JPGs from HTTP to page folder

I am trying to migrate posts from a Wordpress database to Kirby pages.

I use some “spaghetti” code which saves locally a page for each WP post:

Post-id: 4163
----
Post-name: lorem-ipsum    
----    
Guid: http://www.oldwebsite.com/?p=4163
----
Post-title: Lorem Ipsum    
----
Post-content: 

<img class="alignnone size-large wp-image-3591" title="Lorem Ipsum" src="http://www.oldwebsite.com/wp-content/uploads/2011/12/Image.jpg" alt="" width="710" height="462" />

Nullam id dolor id nibh ultricies vehicula ut id elit. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Maecenas sed diam eget risus varius blandit sit amet non magna.

I would like to extract each image from Post-Content and have it saved into each Kirby page folder. How can I do it? The following is the code I am using to do the rest.

<?php $wp_term_relationships = db::select('wp_term_relationships', '*'); ?>
<?php $wp_terms = db::select('wp_terms', '*'); ?>
<?php $wp_posts = db::select('wp_posts', '*'); ?>


<?php foreach($wp_term_relationships as $each): ?>
	<?php if ($post = $wp_posts->filterBy('ID', $each->object_id())->first()): ?>
		
		<?php $term_name = $wp_terms->filterBy('term_id', $each->term_taxonomy_id())->first()    ; ?>
		
		<?php
		$value = $post->post_content();
		$pattern = '/http.*jpg/';
		preg_match($pattern, $value, $matches);
		?>
		
		<?php foreach ($matches as $match): ?>
			<?php echo $match ?>
		<?php endforeach ?>
		
		<?php try {
			$newPage = $page->children()->create($post->post_name(), 'project', array(
				'object_id'     => $each->object_id(),
				'post_name' 	 => $post->post_name(),
				'guid'      	 => $post->guid(),
				'post_title'    => $post->post_title(),
				'post_content'  => $post->post_content(),
				'tag'      		 => $term_name->name(),
				));
			echo 'The page has been created';
		} 
		
		catch(Exception $e) {
			echo 'The page could not be created';
		} ?>
	<?php endif ?>
<?php endforeach ?>

If your RegEx to get the images already works, you can use the following code to download the image to the page:

file_put_contents($newPage->root() . DS . basename($match), fopen($match, 'r'));

This will download the images and place them into your page folders. Please note that you need to change the order in the code: First create the page object and then download the images from the old site.