我試着在這裏關注一些關於preg_match和DOM的問題,但是一切都飛到我頭上.
我有一個像這樣的字符串:
$String = '<td class="borderClass" width="225" style="border-width: 0 1px 0 0;" valign="top"> <div style="text-align: center;"> <a href="http://myanimelist.net/anime/10800/Chihayafuru/pic&pid=35749"> <img src="http://cdn.myanimelist.net/images/anime/3/35749.jpg" alt="Chihayafuru" align="center"> </a> </div>';
我現在正試圖從中獲取圖像src屬性值.我嘗試使用這段代碼,但我無法弄清楚我做錯了什麼.
$doc = new DOMDocument(); $dom->loadXML( $String ); $imgs = $dom->query("//img"); for ($i=0; $i < $imgs->length; $i++) { $img = $imgs->item($i); $src = $img->getAttribute("src"); } $scraped_img = $src;
我如何使用PHP獲取圖像src屬性?
解決方法:
以下是您可以使用的更正代碼:
$String = '<td class="borderClass" width="225" style="border-width: 0 1px 0 0;" valign="top"> <div style="text-align: center;"> <a href="http://myanimelist.net/anime/10800/Chihayafuru/pic&pid=35749"> <img src="http://cdn.myanimelist.net/images/anime/3/35749.jpg" alt="Chihayafuru" align="center"> </a> </div>'; $doc = new DOMDocument(); libxml_use_internal_errors(true); $doc->loadHTML( $String ); $xpath = new DOMXPath($doc); $imgs = $xpath->query("//img"); for ($i=0; $i < $imgs->length; $i++) { $img = $imgs->item($i); $src = $img->getAttribute("src"); } echo $src;
OUTPUT
http://cdn.myanimelist.net/images/anime/3/35749.jpg