以下を使用して、html ページを解析し、画像を返します。
$html = file_get_html($url);
foreach($html->find('img') as $e){
$image = $e->src;
}
理想的には、拡張子が .jpg のファイルのみを表示したいのですが、おそらく preg_match を使用できることはわかっていますが、より効率的な方法はありますか?
以下を使用して、html ページを解析し、画像を返します。
$html = file_get_html($url);
foreach($html->find('img') as $e){
$image = $e->src;
}
理想的には、拡張子が .jpg のファイルのみを表示したいのですが、おそらく preg_match を使用できることはわかっていますが、より効率的な方法はありますか?
pathinfo()
探しているネイティブ PHP 関数です。はい、必要に応じて文字列を操作できますが、「正しい」方法を探している場合は、次のとおりです。
$html = file_get_html($url);
// file extensions we are looking for
$allowedExtensions = ['jpg', 'jpeg', 'jpe'];
foreach($html->find('img') as $el){
// file extensions are usually treated as case insensitive, but the
// implied comparison operator used with in_array() is case sensitive
// so normalise the data to lower-case.
$extension = strtolower(pathinfo($el->src, PATHINFO_EXTENSION));
if (in_array($extension, $allowedExtensions)) {
// File has a JPEG-like file extension
}
}
あなたのコードは問題ありません。これはあなたのケースでうまくいくでしょう
// Create DOM from URL or file
$html = file_get_html('http://www.yahoo.com/');
// Find all images
foreach($html->find('img') as $element)
{
$img = strtolower($element->src);
if(pathinfo($img,PATHINFO_EXTENSION) == "jpg")
echo $element->src . '<br>';
}
$split = explode(".", $image);
$extention = $split[count($split)-1];