Reputation: 83
I've already search about this but most of the topics used java language, but i need using DOM in PHP. I wanna extract this element from example.com :
<div id="download" class="large-12 medium-12 columns hide-for-small-only">
<a href="javascript:void(0)" link="https://mediamusic.com/media/mp3/mp3-256/Mas.mp3" target="_blank" class="mp3_download_link">
<i class="fa fa-cloud-download">Download Now</i>
</a>
</div>
How can i get mp3_download_link
class from this code using DOM in PHP! as i said i have already search about this but really i confused...
Upvotes: 0
Views: 444
Reputation: 969
Let's assume you have this DOM as a string. Then you may use built-in DOM extension to get link you need. Here is the example of a code:
$domstring = '<div id="download" class="large-12 medium-12 columns hide-for-small-only">
<a href="javascript:void(0)" link="https://mediamusic.com/media/mp3/mp3-256/Mas.mp3" target="_blank" class="mp3_download_link">
<i class="fa fa-cloud-download">Download Now</i>
</a>
</div>';
$links = array();
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($domstring);//here $domstring is a string containing html you posted in your question
$node_list = $dom->getElementsByTagName('a');
foreach ($node_list as $node) {
$links[] = $node->getAttribute('link');
}
print_r(array_shift($links));
Upvotes: 0
Reputation: 176
You can try file_get_html to parse html
$html=file_get_html('http://demo.com');
and use the below to get all the attributes of anchor tag.
foreach($html->find('div[id=download] a') as $a){
var_dump($a->attr);
}
Upvotes: 0
Reputation: 148
You can use library to parsing DOM. For example: https://github.com/tburry/pquery
Usage:
$dom = pQuery::parseStr($html);
$class = $dom->query('#download a')->attr('class');
Upvotes: 1