【问题标题】:How can I extract multiple HTML tags from a MySQL table如何从 MySQL 表中提取多个 HTML 标签
【发布时间】:2016-12-12 06:06:19
【问题描述】:

我在基于 MySQL 的 CMS 中有一个表,其中一个字段包含 CMS 网页中显示的文章文本。

有些文章包含嵌入在文本中的图像,以 HTML 'img' 标签的形式。字段中包含的文本中可能有一张或多张图片。

我想做的是创建一个查询,该查询将提取所有文章中所有图像的列表。我设法创建了一些代码如下:

SELECT nid, 
substr(body,locate('<img', body),(locate('>',body,locate('<img', body)) - locate('<img', body))) as image,
body FROM `node_revisions` where body like '%<img%'

这似乎工作正常,但是当然它只提取第一个图像,我真的很想提取所有图像(事实上,这通常意味着使用循环,但这在 MySQL 中似乎不可能)。

仅供参考,有问题的 CMS 是 Drupal 6,因此是字段和表的名称。然而,这确实是一个关于 MySQL 而不是 Drupal 的问题,这就是为什么我在这里而不是在 Drupal Stackexchange 网站上问的原因。

【问题讨论】:

标签: php html mysql parsing drupal-6


【解决方案1】:

尝试使用 locate()、substring() 或正则表达式来解析 HTML 或 XML 会让自己发疯。见https://blog.codinghorror.com/parsing-html-the-cthulhu-way/

我建议你使用 PHP 的 DOMDocument 类:

<?php

$bodyHtml = "now is the time for all <img src='good.jpg'> men to come to the <img src='aid.jpg'> of their country";

$dom = new DOMDocument();
$dom->loadHTML($bodyHtml);
$imgs = $dom->getElementsByTagName("img");
foreach ($imgs as $img) {
        print "$img->nodeName\n";
        foreach ($img->attributes as $attr) {
                print "  $attr->name=$attr->value\n";
        }
}

输出:

img
  src=good.jpg
img
  src=aid.jpg

【讨论】:

【解决方案2】:

使用正则表达式解析 html 永远不会 100%,您永远不会对自己拥有每张图片并正确格式化感到自信,

您遇到的另一个问题是您在问题中暗示的问题。您在 node_revisions 中有一条记录,其中可能包含 1、2 或 10,000 张图像。 在 SQL 中,您无法在查询结果中将每个图像作为新行返回,因此您必须将每个图像作为新列返回。

这意味着您实际上需要手动指定每一列:

SELECT code_to_return_img_1 as url1
      ,code_to_return_img_2 as url2
      ,code_to_return_img_3 as url3
      ,code_to_return_img_4 as url4
      ,code_to_return_img_5 as url5
      ,code_to_return_img_6 as url6
      ....
      and so on

如果您知道每篇文章只有不到 20 张图片,并且您没有 php/java/python 可供您使用,而这只是您需要的一次性 hack 工作,那么您可以使用正则表达式来完成和 SQL,但你 30 分钟的工作可能会变成 2 天的工作和爆裂的静脉。

如果 Java 是一个选项: https://jsoup.org/

如果 Python 是一个选项: https://docs.python.org/2/library/htmlparser.html

如果 PHP 是一个选项: http://htmlparsing.com/php.html

$dom = new DOMDocument;
$dom->loadHTML($html);
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
    $imgurl = $image->getAttribute('src');
}

【讨论】:

    猜你喜欢
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 2021-11-24
    相关资源
    最近更新 更多