user1788736
user1788736

Reputation: 2845

How to get <a href= value inside div with class name only?

I am trying to get value of href inside a div with class name(class="visible-xs"). I tried this code and it gets all the href outside div as well which I don't want.

$dom = new DOMDocument;
$dom->loadHTML($code2);
foreach ($dom->getElementsByTagName('a') as $node)
{

 echo $node->getAttribute("href")."\n";
}

Then i tried following but it gives me error(Fatal error: Call to undefined method DOMDocument::getElementsByClassName() in..):

$dom = new DOMDocument;
$dom->loadHTML($code2);
foreach ($dom->getElementsByClassName('visible-xs') as $bigDiv) {

   echo $bigDiv->getAttribute("href")."\n";
}

could any one help me fix the above error and only get the value of href inside div with class name visible-xs ?Thanks in advance.

sample data:

<tr class="ng-scope" ng-repeat="item in itemContent">
<td class="ng-binding" style="word-wrap: break-word;">test/folder/1.mp4
<div class="visible-xs" style="padding-top: 10px;">
<!-- ngIf: item.isViewable --> class="btn btn-default ng-scope" ng-click="$root.openView(item);">View</a><!-- end ngIf: item.isViewable -->
<a href="https://somesite.com/test/1.mp4" class="btn btn-default" ng-href="https://somesite.com/test/1.mp4" target="_blank">Download</a>
<a class="btn btn-default" href="javascript:void(0);" ng-click="item.upload()" target="_blank">Upload</a>
</div>
</td>
<!-- ngIf: hasViewables --><td class="text-right hidden-xs ng-scope" style="white-space: nowrap; width: 60px;" ng-if="hasViewables">
<!-- ngIf: item.isViewable -->class="btn btn-default ng-scope" ng-click="$root.openView(item);">View</a><!-- end ngIf: item.isViewable -->
</td><!-- end ngIf: hasViewables -->
<td class="text-right hidden-xs" style="white-space: nowrap; width: 250px;">
<a href="https://somesite.com/test/1.mp4" class="btn btn-default" ng-href="https://somesite.com/test/1.mp4" target="_blank">Download</a>
javascript:void(0);" ng-click="item.upload()" target="_blank">Upload</a>
</td>
</tr>

Upvotes: 0

Views: 1758

Answers (1)

chris85
chris85

Reputation: 23880

There is no getElementsByClassName function. Iterate over your divs, check the class, if matched pull the links inside and output the hrefs you want (or break if you want to stop after the first match).

$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
foreach ($dom->getElementsByTagName('div') as $div) {
     if($div->getattribute('class') == 'visible-xs') {
          foreach($div->getElementsByTagName('a') as $link) {
               echo $link->getattribute('href');
          }
     }
}

Demo: https://eval.in/698484

Example with the break, https://eval.in/698488.

Upvotes: 2

Related Questions