Php 使用DOM从url提取html

Php 使用DOM从url提取html,php,dom,xpath,Php,Dom,Xpath,我已经搜索过了,但是大多数主题都使用java语言,但是我需要在PHP中使用DOM。我想从example.com中提取此元素: <div id="download" class="large-12 medium-12 columns hide-for-small-only"> <a href="javascript:void(0)" link="https://mediamusic.com/media/mp3/mp3-256/Mas.mp3" target="_blank

我已经搜索过了,但是大多数主题都使用java语言,但是我需要在PHP中使用DOM。我想从example.com中提取此元素:

<div id="download" class="large-12  medium-12  columns hide-for-small-only">
  <a href="javascript:void(0)" link="https://mediamusic.com/media/mp3/mp3-256/Mas.mp3" target="_blank" class="mp3_download_link">
  <i class="fa fa-cloud-download">Download Now</i>
  </a>
</div>

如何使用PHP中的DOM从这段代码中获取mp3_download_link类!正如我所说,我已经搜索过了,但我真的很困惑…

您可以使用库解析DOM。例如:

用法:

$dom = pQuery::parseStr($html);
$class = $dom->query('#download a')->attr('class');
您可以尝试使用file\u get\u html来解析html

$html=file_get_html('http://demo.com');
并使用下面的命令获取锚定标记的所有属性

foreach($html->find('div[id=download] a') as $a){
  var_dump($a->attr);
}

假设这个DOM是一个字符串。然后,您可以使用内置的DOM扩展来获取所需的链接。下面是一个代码示例:

$domstring = '<div id="download" class="large-12  medium-12  columns hide-for-small-only">
  <a href="javascript:void(0)" link="https://mediamusic.com/media/mp3/mp3-256/Mas.mp3" target="_blank" class="mp3_download_link">
    <i class="fa fa-cloud-download">Download Now</i>
  </a>
</div>';
$links = array();
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($domstring);//here $domstring is a string containing html you posted in your question
$node_list = $dom->getElementsByTagName('a');

foreach ($node_list as $node) {
  $links[] = $node->getAttribute('link');
}

print_r(array_shift($links));

你试过什么吗?@u_mulder是的,getElementsByTagName,但我需要从html代码中提取该类只需在其上使用array_shift,如果你需要链接的类值,请在foreach loopthanx bro中使用getAttribute'class',但不幸的是它还没有工作!白色屏幕您是否在第3行向其发送了正确的$domstring?再次检查我的示例。我已经在其中发布了完整的工作代码。@alex_edav Yes thanx!但我在url中设置了$domstring值。这个怎么样?我可以设置url然后它自动打印那个url吗?