2016-08-05 151 views
0

我在基于MySQL的CMS中有一个表,其中一个字段包含显示在CMS网页中的文章的文本。如何从MySQL表中提取多个HTML标记

某些文章包含以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站点上问的原因。

+0

我建议的东西像PHP这样做而不是MySQL。 [这个答案](http://stackoverflow.com/questions/6449072/doing-calculations-in-mysql-vs-php#answer-6449162)可能是内容丰富的。这里是[另一篇文章](https://www.quora.com/What-is-faster-for-calculations-in-MySQL-or-PHP)。 – showdev

回答

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 
+0

工作得很好,对于Drupal开发人员参考,我能够使用[Views PHP模块](https://www.drupal。org/project/views_php)在视图中生成相应的输出,[如本文档中所述](https://www.drupal.org/node/2088039) –

0

解析与正则表达式的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 /蟒蛇在你的处置,这只是一个你需要的黑客工作,然后你可以用正则表达式和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'); 
} 
相关问题