PHP-通过div ID设置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时,一切显示正常.但是,当我尝试仅回应筹集的美元金额时,什么也没有出现.
解决方法:
像这样更改爆炸代码:
$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
标签:file-get-contents,php 来源: https://codeday.me/bug/20191028/1953435.html