dadamssg87 Posted September 21, 2012 Share Posted September 21, 2012 I've been pulling my hair out over this. I have a web page that i'm trying to get the contents of all of the divs with a certain class. I figured xpath would be the best way to go but i can't figure it out and theres a surprising lack of examples/tutorials about using it with HTML. i have the following and i know i'm getting the right number of divs. I just don't know how to get their innerHTML/contents. $url = "http://www.vanityfair.com/politics/2012/10/michael-lewis-profile-barack-obama"; $ctx = stream_context_create(array('http'=> array('timeout' => 10))); libxml_use_internal_errors(TRUE); $num = 0; if($html = @file_get_contents($url,false,$ctx)){ $doc = DOMDocument::loadHTML($html); $xpath = new DOMXPath($doc); foreach($xpath->query('//div[@class="page-display"]') as $div){ $num++; echo "$num. "; // echo $div->item(0)->textContent; //???? echo "<br/>"; } echo "<br/>FINISHED"; } The $div->item(0)->textContent line breaks the loop and doesn't output anything. Quote Link to comment https://forums.phpfreaks.com/topic/268631-xpath-get-contents-of-div-with-certain-class/ Share on other sites More sharing options...
Maq Posted September 21, 2012 Share Posted September 21, 2012 The div with the class "page-display" is empty. You should probably match on a class such as "pageContainers". Quote Link to comment https://forums.phpfreaks.com/topic/268631-xpath-get-contents-of-div-with-certain-class/#findComment-1379804 Share on other sites More sharing options...
Maq Posted September 21, 2012 Share Posted September 21, 2012 For example, if you just want the content: foreach($xpath->query('//div[@class="pageContainers"]') as $div { echo $div->getElementsByTagName("p")->item(0)->nodeValue; echo "\n\n"; } Quote Link to comment https://forums.phpfreaks.com/topic/268631-xpath-get-contents-of-div-with-certain-class/#findComment-1379806 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.