2016-08-05 153 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'); 
} 
相關問題