猿问

如何使用 PHP DOMDocument() 检索子元素内的值?

我有一个$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,但它不起作用。


我错过了什么?


人到中年有点甜
浏览 157回答 1
1回答

慕容3067478

您可以做的是查看<img>标签中的下一个元素(使用nextSibling),如果这是一个<figcaption>元素,则将标题文本设置为其文本内容,否则将其设置为空白...if (preg_match('#/storage/(.*)/articles/pictures/(.*)#', $src, $result)) {&nbsp; &nbsp; $caption = $img->nextSibling;&nbsp; &nbsp; if ( $caption->localName == "figcaption" )&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $captionText = $caption->textContent;&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $captionText = "";&nbsp; &nbsp; }&nbsp; &nbsp; $imgs[] = [&nbsp; &nbsp; &nbsp; &nbsp; 'id'&nbsp; &nbsp; &nbsp; => $result[1],&nbsp; &nbsp; &nbsp; &nbsp; 'name'&nbsp; &nbsp; => $result[2],&nbsp; &nbsp; &nbsp; &nbsp; 'caption' => $captionText,&nbsp; &nbsp; ];}
随时随地看视频慕课网APP
我要回答