我有一個$body從帖子中檢索的變量。用戶可能會也可能不會發(fā)布圖片。當它發(fā)布圖片時,我必須檢索有關(guān)圖片的一些信息,有時用戶可能會為圖片寫一個標題。這是沒有標題的html :<figure class="image"><img src="/storage/5/articles/pictures/asdf87.jpeg"></figure>這是一個帶有標題的示例:<figure class="image"><img src="/storage/5/articles/pictures/asdf87.jpeg"><figcaption>test_caption</figcaption></figure>這是我到目前為止的代碼: $dom_err = libxml_use_internal_errors(true); $dom = new \DOMDocument(); $dom->loadHtml($body, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $xpath = new \DOMXPath($dom); $imgs = []; foreach ($xpath->query("//figure/img") as $img) { $src = $img->getAttribute('src'); if (preg_match('#/storage/(.*)/articles/pictures/(.*)#', $src, $result)) { $imgs[] = [ 'id' => $result[1], 'name' => $result[2], 'caption' => $img->item(0)->textContent, ]; } } libxml_clear_errors(); libxml_use_internal_errors($dom_err);我正在嘗試檢索這部分代碼中的標題'caption' => $img->item(0)->textContent,但它不起作用。我錯過了什么?
1 回答

慕容3067478
TA貢獻1773條經(jīng)驗 獲得超3個贊
您可以做的是查看<img>標簽中的下一個元素(使用nextSibling),如果這是一個<figcaption>元素,則將標題文本設(shè)置為其文本內(nèi)容,否則將其設(shè)置為空白...
if (preg_match('#/storage/(.*)/articles/pictures/(.*)#', $src, $result)) {
$caption = $img->nextSibling;
if ( $caption->localName == "figcaption" ) {
$captionText = $caption->textContent;
}
else {
$captionText = "";
}
$imgs[] = [
'id' => $result[1],
'name' => $result[2],
'caption' => $captionText,
];
}
- 1 回答
- 0 關(guān)注
- 175 瀏覽
添加回答
舉報
0/150
提交
取消