在html标记中解析Json数据

时间:2013-04-26 20:41:21

标签: php regex json

我需要在网页的脚本中提取一个json对象。这是网页的一部分:

<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>

我想提取以{ maptype:开头的JSON对象。我想过使用regular expression方法来实现这一目标。这是我做的:

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

但是,我的模式似乎只选择了对象的第一行!我无法想办法让它选择所有对象。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

Elsalamoe 3aleikom:D

这是你如何做到的:

$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 :(得分:0)

您的模式失败的原因是点.与换行符不匹配,如果您需要,则必须在模式的末尾添加s修饰符。多线模式(m修饰符)在这里没用。

试试这个:

$json = (preg_match('~\.gMap\s*+\(\s*+\K\{.+?\}(?=\s*+\)\s*+;)~s', $html, $result))?
    $result[0] : false;