div id的file_get_contents

时间:2015-03-13 17:49:40

标签: php file-get-contents

我正在尝试从外部网页(https://uconn.givecorps.com/projects/3120-uconn-marching-band-tower-project)获取特定div(id =“total_raised”)的内容。这是我的代码:

$url = 'https://uconn.givecorps.com/projects/3120-uconn-marching-band-tower-project';
$content = file_get_contents($url);
$first_step = explode( '<div id="total_raised">' , $content );
$second_step = explode("</div>" , $first_step[1] );

echo $second_step[0];

当我回复$ content时,一切都很好。但是,当我试图回应所筹集的美元金额时,没有任何信息显示出来。

1 个答案:

答案 0 :(得分:4)

更改爆炸代码如下:

$first_step = explode( "id='total_raised'>" , $content );
$second_step = explode("<span>" , $first_step[1] );
$raised = trim($second_step[0]);

或者您可以使用DOMDocument来更精确地执行此操作:

$url = 'https://uconn.givecorps.com/projects/3120-uconn-marching-band-tower-project';
$content = file_get_contents($url);

$doc = new DOMDocument();
$doc->loadHtml($content);

$raised = explode("\n", trim($doc->getElementById('total_raised')->nodeValue))[0];

echo $raised; // $2,405