【问题标题】:How would I parse this html in php?我将如何在 php 中解析这个 html?
【发布时间】:2017-03-14 03:23:57
【问题描述】:

我已将我的 Firefox 书签导出为 html,因此我可以将我丰富的音乐收藏下载到我的手机上,我的问题是没有我知道的简单方法。

我的意图是使用 PHP 将 html 解析为 URL 数组

这是 html 的样子

<DT><A HREF="https://www.youtube.com/watch?v=Ue8PpA557Bc" ADD_DATE="1477165404" LAST_MODIFIED="1477165404" ICON_URI="https://s.ytimg.com/yts/img/favicon_144-vflWmzoXw.png" ICON="data:image/png;base64,">Don Diablo - Knight Time (Official Music Video) - YouTube</A>

我该怎么做?

【问题讨论】:

  • 抱歉,我试图使用块引用。
  • 在这种情况下,我认为以下任何一个答案都对您有用。您还可以在下面的线程中看到其他选项。

标签: php html parsing firefox


【解决方案1】:

如果您在$html 中输入了正确的html 字符串,您可以使用DOMDocument 解析字符串并使用XPath 选择href 属性。

<?php

$html = '<DT><A HREF="https://www.youtube.com/watch?v=Ue8PpA557Bc" ADD_DATE="1477165404" LAST_MODIFIED="1477165404" ICON_URI="https://s.ytimg.com/yts/img/favicon_144-vflWmzoXw.png" ICON="data:image/png;base64,">Don Diablo - Knight Time (Official Music Video) - YouTube</A>';

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DomXPath($doc);

$nodeList = $xpath->query("//a/@href");

$links_array = [];

foreach($nodeList as $node){
  $links_array[] = $node->nodeValue;
}

echo "<pre>";
print_r($links_array);
echo "</pre>";

这里的输出是:

大批 ( [0] => https://www.youtube.com/watch?v=Ue8PpA557Bc )

【讨论】:

  • 这将与
    标签一起使用还是我需要删除它们?
  • @Adam 欢迎!我很高兴这有帮助!
【解决方案2】:
$doc = new DOMDocument();
$doc->loadHTML($bookmarks);
foreach ($doc->getElementsByTagName("a") as $node) { 
    $urls[] = $node->getAttribute("href");
}

【讨论】:

  • 虽然这段代码可以解决提问者的问题,但最好解释一下它是如何工作的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-16
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2020-03-19
相关资源
最近更新 更多