我有一个$body从帖子中检索的变量。用户可能会也可能不会发布图片。当它发布图片时,我必须检索有关图片的一些信息,有时用户可能会为图片写一个标题。这是没有标题的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条经验 获得超3个赞
您可以做的是查看<img>标签中的下一个元素(使用nextSibling),如果这是一个<figcaption>元素,则将标题文本设置为其文本内容,否则将其设置为空白...
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 关注
- 156 浏览
添加回答
举报
0/150
提交
取消