Search code examples
phpweb-scrapingpreg-matchfile-get-contentspreg-match-all

php preg_match_all get second select box options


I am applying preg_match_all on a webpage select box that i get from file_get_contents but the problem is that it is only getting first select box and is not able to get second select box and it's options. My code is

 $html = file_get_contents("https://www.amazon.co.jp/-/en/dp/B09C1PM7K3?th=1");
 $quantityMatch  = preg_match_all( '@(<option value="([^"]+)">([^<]+)</option>)@', $html, $quantity);

    $result = array();
    $k = 0;
    foreach ($quantity[0] as $i => $value){
        $result[$quantity[2][$i]] = $quantity[3][$i];
        $k = $i;
    }
    $finalQty = $quantity[3][$k];
    // print_r($result);
    dd($finalQty);

it is getting categories from this page but i need second select box that is the quantity of stock on the webpage.


Solution

  • You can see the data of the selected option with this link. unselected if you search with a phrase like "<li"

    <li ... data-dp-url="/dp/B09C1P6T71/ref=twister_B09GWCBGQ5?_encoding=UTF8&psc=1"
    

    you can get data-dp-url for unselected option and you add your link etc: https://www.amazon.co.jp/-/en/ and again file get content new url that's your new option stock :)

    Example: your new second option link:

    https://www.amazon.co.jp/-/en/dp/B09C1Q11Z9/ref=twister_B09GWCBGQ5?_encoding=UTF8&psc=1
    

    If you don't understand, I can write sample code and post it.

    enter image description here Red: unselected option Black: selected option

    For example second option product stock count:

    $html = file_get_contents("https://www.amazon.co.jp/-/en/dp/B09C1PM7K3?th=1");
        $qq = preg_match_all( '@(data-dp-url="([^<]+)" )@', $html, $option);
        $link = "https://www.amazon.co.jp/-/en".str_replace("&amp;", '&', explode('"', $option[0][1])[1]);
        $html_new_option = file_get_contents($link);
        $quantityMatch  = preg_match_all( '@(<option value="([^"]+)">([^<]+)</option>)@', $html_new_option, $quantity);
    
        $result = array();
        $k = 0;
        foreach ($quantity[0] as $i => $value){
            $result[$quantity[2][$i]] = $quantity[3][$i];
            $k = $i;
        }
        $finalQty = $quantity[3][$k];
        dd($finalQty);
    

    => $option[0][WANT_OPTION_ORDER]