Reputation: 3042
Retrieving a value inside of a span id?
<span id="playerCount">157,767 people currently online</span>
How would I go about getting the value inside that ID? I thought of preg_match() but is that even safe?
Upvotes: 0
Views: 160
Reputation: 942
With Regex this is possible and very easy. If it were something more advanced I'd instantly recommend using a tool created for parsing HTML (see 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);
Upvotes: 0
Reputation: 34107
Use php's DOM methods. The following code assumes you have allow_url_fopen enabled:
$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;
Upvotes: 4