要將整個HTML片段轉換爲TCPDF正如你所提到在你的評論中,你需要用DOMDocument
解析這個片段,然後遍歷每個子節點,決定如何正確處理它們。
<html>
<body>
Some text
<p>A paragraph</p>
<img src="image1.jpg" width="200" height="200">
More text
<img src="image2.jpg" width="200" height="200">
</body>
</html>
:
與您在上面提供的片段美中不足的是,它不是一個完整的HTML文檔,從而DOMDocument
將<html>
和<body>
標籤解析它的時候,內部裝載以下結構把它包
然而,這個警告很容易解決,通過建立在@ hakre的答案在我鏈接到下面的線程。我的建議是沿着以下線的東西:
// Load the snipped into a DOMDocument
$doc = new DOMDocument();
$doc->loadHTML($content);
// Use DOMXPath to retrieve the body content of the snippet
$xpath = new DOMXPath($doc);
$data = $xpath->evaluate('//html/body');
// <body> is now $data[0], so for readability we do this
$body = $data[0];
// Now we loop through the elements in your original snippet
foreach ($body->childNodes as $node) {
switch ($node->nodeName) {
case 'img':
// Get the value of the src attribute from the img element
$src = $node->attributes->getNamedItem('src')->nodeValue;
$this->Image($src, PDF_MARGIN_LEFT, $y_offset, 116, 85);
break;
default:
// Pass the line to TcPDF as a normal paragraph
break;
}
}
這樣,您就可以輕鬆地添加額外的case 'blah':
塊來處理可能出現在你的$content
片段,並適當地處理它們的其他元素,內容將是按照正確的順序進行處理,而不會破壞文本的原始流程。 :)
- 原始回答。如果你只是想提取圖像源並在其他地方獨立處理它們,它們將會起作用。
您可以通過使用正則表達式匹配所有在您$content
字符串<img>
標籤:
/<img(?:[\s\w="]+)src="([^"]+)"(?:[\s\w="]*)\/?>/i
,你可以玩,看看它是如何工作的正則表達式的現場故障是在這裏:http://regex101.com/r/tS5xY9
您可以使用此正則表達式與preg_match_all()
從您$content
變量中檢索所有的圖像標籤如下:
$matches = array();
$num = preg_match_all('/<img(?:[\s\w="]+)src="([^"]+)"(?:[\s\w="]*)\/?>/i', $content, $matches, PREG_SET_ORDER);
的PREG_SET_ORDER
恆定告訴preg_match_all()
存儲其以這樣的方式的結果產生輸出時,其更容易通過環狀,作爲陣列上的第一索引(即,$matches[0]
,$matches[1]
等)將包含完整的組匹配結果從正則表達式。在上述正則表達式的情況下,將$matches[0]
包含以下內容:
array(
0 => '<img src="image1.jpg" width="200" height="200">',
1 => 'image1.jpg',
)
您現在可以遍歷$matches
爲$key => $match
並通過$match[1]
您$this->Image()
方法。
或者,如果不通過要循環,你可以直接從$matches
訪問每個src
屬性爲$matches[0][1]
,$matches[1][1]
等
如果您需要能夠給內訪問其他屬性標籤,那麼我建議您使用Get img src with PHP上的@hakre提供的DOMDocument
方法。如果您只需要訪問src
屬性,那麼使用preg_match_all()
會更快更高效,因爲它不需要將片段的整個DOM作爲對象加載到內存中,以便爲您提供所需的數據。
此鏈接可能會幫助你http://stackoverflow.com/questions/10130858/get-img-src-with-php – Chitowns24
Downvoting因爲你的問題沒有表現出任何努力來解決你的問題 - 你只是要求我們代碼給你。 –
啊哈,我不知道從哪裏開始。無論如何@RobertRossmann GAL;) – Martin