2016-07-12 14 views
0

私は画像リンクとhrefを見つける必要があります。 show href、img src、およびaltタグ。xpathを使用してextrafをhref、src、altを解析する方法

は、ここに私のコード

$xpath = new DOMXPath('http,://.....'); 


foreach ($xpath->query('//a[@href]//img') as $img) { 


echo '<a href=' .'"' .$img['href'] .'"' .'/>' .'<img src="' .$img['src'] .'"' .'alt="' .$img['alt'] .'"/>' .'</a>'; 



Catchable fatal error: Argument 1 passed to DOMXPath::__construct() must be an  
instance of DOMDocument, string given, called in 

あなたは私を助けることはできますか?

+0

負荷 ' DOMDocument'を実行してから、DOMXpathを使用して直接URLをダンプすることはできません – Ghost

+0

参考までに:[PHPでHTML/XMLをどのように解析して処理しますか?](ht tp://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – FirstOne

答えて

0

あなたは以下のコード

$dom = new DOMDocument(); 
libxml_use_internal_errors(true); 
$dom->loadHTMLFile('http://example.com/'); 

$xpath = new DOMXpath($dom); 

を使用することができ、その後のリンクから画像srcを取得するために

にそれを使って編集を行うには、あなたがやりたいために、XPathを使用し

# get the images inside a link 
foreach ($xpath->query('//a[@href]//img') as $img) { 

    # find all the links and images  
    for ($link = $img; $link->tagName !== 'a'; $link = $link->parentNode); 

    $output[] = array(
     'href' => $link->getAttribute('href'), 
     'src' => $img->getAttribute('src'), 
     'alt' => $img->getAttribute('alt'), 
    ); 
} 
+0

空白、表示できません エコー '' .'' .''; – vallez

+0

あなたの要件に合わせて私の答えを変更した、私は応答が遅すぎると思うが、それは他の誰かを助けるかもしれない – Dharam

関連する問題