douxin8383 2013-04-26 20:41
浏览 50
已采纳

在html标记中解析Json数据

I need to extract a json object inside a web page's script. This is a part of the web page:

<html>
<script>
    .....
</script>
<script type=\"text/javascript\">
    $(function(){



        $(\"#map5\").gMap({ maptype: G_SATELLITE_MAP,
        controls: false,
                  scrollwheel: false,

                  markers: [

{.....},{......},],

latitude: 24.70115790054175,
longitude: 46.04358434677124,
zoom: 5
});

});
</script>
</head>
<body>
    ....
</body>
</html>

I want to extract the the JSON object that starts wit { maptype:. I thought of using regular expression approach to achieve this. Here is what I did:

$html = file_get_contents($url);
$regex_pattern = "/\<script.*/";
preg_match_all($regex_pattern,$html,$matches);

However, my pattern seems to select the first line of the object only! I couldn't figure out a way to make it select all the object.

Any help will be appreciated.

  • 写回答

2条回答 默认 最新

  • dpmpa26468 2013-04-26 21:01
    关注

    Elsalamoe 3aleikom :D

    Here's how you do it:

    $script = <<<FIL
    <script type=\"text/javascript\">
        $(function(){
    
    
    
            $(\"#map5\").gMap({ maptype: G_SATELLITE_MAP,
            controls: false,
                      scrollwheel: false,
    
                      markers: [
    
    {.....},{......},],
    
    latitude: 24.70115790054175,
    longitude: 46.04358434677124,
    zoom: 5
    });
    
    });
    </script>
    FIL;
    
    preg_match_all('/<script[^>]*>.*?\.gMap\(\s*({.*?})\);.*?<\/script>/mis', $script, $m);
    var_dump($m[1]);
    

    Online demo with explanation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致