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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongxie8906 2013-04-26 22:25
    关注

    The reason your pattern fail is that the dot . don't match newlines, if you want it does, you must add the s modifier at the end of your pattern. The multiline mode (m modifier) is not useful here.

    Try this:

    $json = (preg_match('~\.gMap\s*+\(\s*+\K\{.+?\}(?=\s*+\)\s*+;)~s', $html, $result))?
        $result[0] : false;
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 win10商店接入问题
  • ¥15 java 这种树形框吗
  • ¥40 找同学帮敲Python代码
  • ¥15 MYSQL 订单的商品明细重复计算问题
  • ¥15 微信实时共享位置修改
  • ¥100 TG的session协议号转成直登号号后客户端登录几分钟后自动退出设备
  • ¥50 共模反馈回路的小信号增益
  • ¥15 arduino ssd1306函数与tone函数放歌代码不兼容问题
  • ¥70 0.96版本hbase的row_key里含有双引号,无法deleteall
  • ¥15 诊断性META分析合并效能的检验