file_get_contents 通过 div id
file_get_contents by div id
我正在尝试从外部网页 (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; // ,405
我正在尝试从外部网页 (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; // ,405