I replace the image links in the text with the following format.
{#img='xxxx-xxxx-xxxx-xxxx.abc', alt=''}
Before changing, I get the src
part from the image links and download it to the server with the help of CURL. I do UUID naming for each image downloaded.
All good so far!
$newImageName = create_uuid();
$ch = curl_init($img->getAttribute('src'));
$fp = fopen('/PATH_SAMPLE/' . $newImageName . '.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
However; each image has a different UUID, but as a result of the reformat, the final UUID is rendered to the text; for example like this;
asdasd {#img='19a1cb87-009b-4495-be22-68fb08db8a76', alt=''} asdasd {#img='19a1cb87-009b-4495-be22-68fb08db8a76', alt=''}
All Code;
$jsonFile = "asdasd <img src='https://example.com/image_1.png'> asdasd <img src='https://example.com/image_1.jpg'>";
$dom = new DOMDocument;
$dom->loadHTML($jsonFile);
$imgs = $dom->getElementsByTagName('img');
$imgURLs = [];
foreach ($imgs as $img) {
if (!$img->hasAttribute('src')) {
continue;
} else {
$newImageName = create_uuid();
$ch = curl_init($img->getAttribute('src'));
$fp = fopen('/PATH_SAMPLE/' . $newImageName . '.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$str = preg_replace('/<img[^>]*src=([\'"])(.*?)\1>/', "{#img='" . $newImageName . "', alt=''}", $jsonFile);
}
}
How can I fix the UUID problem for images?