0

I'm using simple_html_dom.php function to scrap data to specific Magento site. I am able to scrap all of the things but can't able to find additional images which are comes from script type="text/x-magento-init" I tried all the way but can't able to fetch. Here are some sample code which I tried. Is it possible to scrap data from scrip tag which are available image in it?

> $scripts = $html->find('script',19);
>     forforeach ($scripts->find("<tag>") as $<tag>) 
>     {
>         foreach ($<tag>->find("img") as $img) //Start searching for img tag in all (divs) you found
>         {
>             echo $img->src . "<br>"; //Output the information from the img's src attribute (if the found tag is <img
> src="www.example.com/cat.png"> you will get www.example.com/cat.png as
> result)
>         }
>     }

Please find the attachedimage

Thanks in advance

0

1 Answer 1

1

managed to get image urls ran script in laravel using simple_html_dom

<?php
require __DIR__ . '/../../../vendor/autoload.php';

use simplehtmldom\HtmlDocument;

function scrapeImagesFromScriptTag($url) {
    $html = file_get_contents($url);

    if (!$html) {
        die("Failed to load the HTML content.");
    }
    
    $dom = new HtmlDocument();
    $dom->load($html);

    $scriptTag = $dom->find('script[type="text/x-magento-init"]', 14); // Adjust index if needed

    if ($scriptTag) {
        $scriptContent = $scriptTag->innertext;

        if (empty($scriptContent)) {
            echo "Script content is empty for the found tag.<br>";
            return;
        }

        echo "<pre>";
        echo htmlspecialchars($scriptContent);
        echo "</pre>";

        $scriptContent = html_entity_decode($scriptContent);
        $data = json_decode($scriptContent, true);

        if ($data !== null) {
            if (isset($data['[data-gallery-role=gallery-placeholder]']['mage/gallery/gallery']['data'])) {
                $images = $data['[data-gallery-role=gallery-placeholder]']['mage/gallery/gallery']['data'];
                foreach ($images as $image) {
                    if (isset($image['img'])) {
                        echo "Image URL: " . $image['img'] . "<br>";
                    }
                }
            } else {
                echo "Expected data structure not found in JSON.";
            }
        } else {
            echo "Error decoding JSON: " . json_last_error_msg();
        }
    } else {
        echo "Script tag not found!";
    }

    $dom->clear();
    unset($dom);
}

ini_set('user_agent', 'My-Application/2.5');

$url = 'https://testurl.com/index.php/sku';  // Replace with actual URL
scrapeImagesFromScriptTag($url);
?>

and got this resultenter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.