0

使用 javascript 或 php,如何从网页中获取值?这是我试图解析的 JSON:

{"error":[""],"templateHtml":"", "_visitor_conversationsUnread":"0","_visitor_alertsUnread":"0"}

我正在尝试获取“_visitor_alertsUnread”的值。我该怎么做呢?

谢谢!

4

2 回答 2

1

您可以使用正则表达式、使用 json 解码或简单索引来解析它。但是,在这三个中,json 是最干净和正确的方法。

1)JSON解码:

$page = file_get_contents($url);
$json_arr = json_decode($string,true);
return $json_arr['_visitor_alertsUnread'];

2)正则表达式:

$page = file_get_contents($url);
$pattern = ".*?_visitor_alertsUnread\\\":\\\"(\\d)\\\"";
preg_match($pattern, $page, $matches);
return $matches[1];

3)索引:

$page = file_get_contents($url);
$needle = "_visitor_alertsUnread";
$startpos = strrpos($page, $needle) + strlen($needle) + 3;
$endpos = strrpos($page, "\"", $startpos);
return substr($page, $startpos, $endpos);
于 2012-06-05T05:23:31.313 回答
0

响应采用 JSON 格式。

如果您只想获取 _visitor_alertsUnread 的值,那么您可以执行类似的操作。

var JSONObj = {"error":["Security error occurred. Please press back, refresh the page, and try again."],"templateHtml":"\n\n\n\n\t</a>\n\t\n\t\tThe following error occurred:</h2>\n\t\t\n\t\t\n\t\t\n\t\t\tSecurity error occurred. Please press back, refresh the page, and try again.</label>\n\t\t\n\t\t</div>\n\t\n</div>","_visitor_conversationsUnread":"0","_visitor_alertsUnread":"0"};

alert(JSONObj._visitor_alertsUnread);
于 2012-06-05T05:17:35.020 回答