Im not sure what you are actually doing here but I think you are looking to create a block of code from the post content then strip unnecessary tags.
I would use strip tags: https://www.w3schools.com/php/func_string_strip_tags.asp
<?php
require "wp-config.php";
// Post Types to include
$args = array(
'posts_per_page' => '50',
'post_type' => array(
'product',
'product-variation'
)
);
// The Query
$query = new WP_Query( $args );
$posts = $query->posts;
foreach($posts as $post) {
$content = $post->post_content;
$content = echo strip_tags($content, "<div><p><h1>"); // where you pass the code block, then state the tags that you wish to keep. I also cannot recall if it will need to be echo'd or not.
}
echo 'Done.'; ?>
Where you pass the code block, then state the tags that you wish to keep. I also cannot recall if it will need to be echo’d or not.
Apologies if I have misunderstood.
Thanks, Jason.