检索范围内的值?
<span id="playerCount">157,767 people currently online</span>
我如何获取该ID内的值?我想到了preg_match(),但这样安全吗?
答案 0 :(得分:4)
使用php的DOM方法。以下代码假定您启用了allow_url_fopen:
$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML(file_get_contents($url));
libxml_use_internal_errors(false);
$span = $domd->getElementById("playerCount");
$span_contents = $span->textContent;
答案 1 :(得分:0)
使用Regex,这是可能的,非常简单。如果它更高级,我会立即建议使用为解析HTML而创建的工具(参见DOMDocument)
<?php
// content containing: '<span id="playerCount">157,767 people currently online</span>';
$content = file_get_contents('http://example.com');
preg_match('/<span id="playerCount">([0-9,]+) people currently online<\/span>/', $content, $matches);
var_dump($matches);