DEV Community

Debajyoti Das
Debajyoti Das

Posted on

Basic web scraping with php

Trying to fetch the above using php.

Image description

    public function __invoke()
    {
        $contents = file_get_contents('https://www.google.com/search?q=gold%20price%20kolkata');
        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $dom->loadHTML($contents);
        libxml_clear_errors();

        $div_contents = $dom->getElementsByTagName('div');
        foreach($div_contents as $element)
        {
            if(str_contains($element->nodeValue, '10g of 24k gold (99.9%)'))
            {
                $prc = substr($element->nodeValue, strpos($element->nodeValue, "10g of 24k gold (99.9%)"), 300);//strpos finds position, substr taking the next 300 characters from the string
                return response()->json(['code'=>200, 'message'=>'Success', 'data'=>$prc], 200);
            }
        }

        return response()->json(['code'=>400, 'message'=>'Not Found', 'data'=>'empty'], 200);
    }

Enter fullscreen mode Exit fullscreen mode

O/p:

Image description

Top comments (0)