如何使用html dom获取script标签下的json数据?

这是我想要获取的数据


 <script>

            window['ads_imgs'] = '{"1734275":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/5\/173\/1734275_chevrolet-aveo-5-usi_7.jpg","11570560":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/0\/115\/11570560_audi-a5-sportback-2012-163cp-impecabila-tinuta-in-garaj_14.jpg","3741462":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/2\/374\/3741462_seat-leon-fr-extra-full-dpf_1.jpg","11596338":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/8\/115\/11596338_toyota-auris-12-115-cp-2016_1.jpg","11687842":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/2\/116\/11687842_opel-astra-h-model-2008_1.jpg","11034666":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/6\/110\/11034666_hyundai-tucson-2008_10.jpg","11596195":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/5\/115\/11596195_volkswagen-passat-20-150-cp-2017_1.jpg","10637740":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/0\/106\/10637740_renault-megane-iii-15-dci-90cp-2017_21.jpg","11884407":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/7\/118\/11884407_audi-a4-

        </script>

我如何使用 html dom 获取 id 和图像链接。这里的代码我得到了确切的脚本,但我无法获取值window['ads_imgs'] 


                //receiving the data from script tag

               $data = $responseData->find('script',11);


                preg_match("/window['ads_imgs'] = '(.*)'/", $data, $m);

                    print_r($m);

                exit();

            }


慕工程0101907
浏览 113回答 1
1回答

开心每一天1111

您的正则表达式中有一个小错误。您需要按如下方式转义方括号。您还需要对外壳使用大括号,因为这是“数据”中显示的实际哨兵:preg_match("/window\['ads_imgs'\] = '{.*}'/", $data, $m);不过,您可能只想要 json 本身。为此,您可以进行另一个正则表达式匹配,$m[0]如下所示:preg_match("/{.*}/", $m[0], $j_str);这是使用示例数据的完整测试:$data = "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;window['ads_imgs'] = '{\"1734275\":\"https:\/\/media2.lajumate.ro\/media\/i\/cart\/5\/173\/1734275_chevrolet-aveo-5-usi_7.jpg\",\"a\":{\"b\":\"bb\"}}'&nbsp; &nbsp; &nbsp; ";preg_match("/window\['ads_imgs'\] = '{.*}'/", $data, $m);preg_match("/{.*}/", $m[0], $j_str);$json = json_decode($j_str[0], true);print_r($json);输出:Array(&nbsp; &nbsp; [1734275] => https://media2.lajumate.ro/media/i/cart/5/173/1734275_chevrolet-aveo-5-usi_7.jpg&nbsp; &nbsp; [a] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [b] => bb&nbsp; &nbsp; &nbsp; &nbsp; ))
打开App,查看更多内容
随时随地看视频慕课网APP