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

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 -->
Download
<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;">
Download
javascript:void(0);" ng-click="item.upload()" target="_blank">Upload</a>
</td>
</tr>

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.

Related

Simple html dom and php fetch hidden content

I am using Simple HTML DOM parser to fetch some data. Everything works great but I am facing a problem when I have enabled the read more plugin on my WordPress site.
The hidden content (the rest content of the article) is inside this div.
A sample:
<div class="mycontent">
Here is some content
<div class="brm" style="display: none;">
Here is another content but it's not vissible because the style of this div is set to display:none
</div>
<p>read more..</p>
</div>
So far I am using:
$url = "www.myurl.com";
$html = new simple_html_dom();
$html->load_file($url);
$maindiv = $html->find('div.mycontent',0)->outertext;
it displays everything except the content inside the div <div class="brm" style="display: none;">
Any ideas how to get the hidden content?
It actually does get that div:
include 'simple_html_dom.php';
$str = <<<EOF
<script type="text/javascript">
<div class="mycontent">
Here is some content
<div class="brm" style="display: none;">
Here is another content but it's not vissible because the style of this div is set to display:none
</div>
<p>read more..</p>
</div>
EOF;
$html = str_get_html($str);
echo $html->find('div.mycontent',0)->outertext;
// <div class="mycontent"> Here is some content <div class="brm" style="display: none;"> Here is another content but it's not vissible because the style of this div is set to display:none </div> <p>read more..</p> </div>

Dueling Regex and DOM Scripts

I'm learning how to work with Bootstrap and jQuery. It looks like I need to do something like this with my articles in order to get some of the special effects (like toggling sections open and closed)...
<section id="introduction">
<h2 class="h2Article" id="a1" data-toggle="collapse" data-target="#b1"><span class="Article"><span class="label label-primary"><small><span class="only-collapsed glyphicon glyphicon-chevron-down"></span><span class="only-expanded glyphicon glyphicon-remove-sign"></span></small> Introduction</span></span></h2>
<div class="divArticle collapse in article" id="b1">
But I have hundreds of articles to put into my database, and writing all that code would take forever. So I put this in my database instead...
<section id="introduction">
<h2 class="h2Article">Introduction</h2>
<div class="divArticle">
Next, I want to use regex or DOM to insert the missing values (preferably regex, as it's easier to work with). In fact, it was working, but now it isn't.
This is my regex script:
$Content = preg_replace('/<h2 class="h2Article">(.*?)<\/h2>/', '<h2 class="h2Article"><span class="Article"><span class="label label-primary"> <small><span class="only-collapsed glyphicon glyphicon-chevron-down"> </span><span class="only-expanded glyphicon glyphicon-remove-sign"></span> </small> $1</span></h2>', $Content);
$Content = preg_replace('/<h3 class="h3Article" id="(.*?)">(.*?) <\/h3>/', '<h3 id="$1" class="Article"><span class="label label- default">$2</span></h3>', $Content);
$Content = preg_replace('/<div class="divArticle">(.*?)<\/div>/', '<div class="divArticle">$1<div style="margin-bottom: 10px; font-size: 150%; text-align: center;"><span class="only-expanded glyphicon glyphicon-remove- sign"></span></div></div>', $Content);
$Content = str_replace('<!-- EndMainDiv -->', '<div class="divClose" style="margin-bottom: 10px; font-size: 150%; text-align: center;"><span class="only-expanded glyphicon glyphicon-remove-sign"></span></div><!-- EndMainDiv -->', $Content);
And this is what the resulting HTML looks like:
<section id="introduction">
<h2 class="h2Article"><span class="Article"><span class="label label- primary"><small><span class="only-collapsed glyphicon glyphicon-chevron- down"></span><span class="only-expanded glyphicon glyphicon-remove-sign"> </span></small> Introduction</span></h2>
<div class="divArticle">
This is my DOM script:
$i = 1; // initialize counter
// initialize DOMDocument
$dom = new DOMDocument;
#$dom->loadHTML($Content); // load the markup
$sections = $dom->getElementsByTagName('section'); // get all section tags
if($sections->length > 0) { // if there are indeed section tags inside
// work on each section
foreach($sections as $section) { // for each section tag
// $section->setAttribute('id', '#a' . $i); // set id for section tag
// get div inside each section
foreach($section->getElementsByTagName('h2') as $h2) {
if($h2->getAttribute('class') == 'h2Article') { // if this div has class maindiv
$h2->setAttribute('id', 'a' . $i); // set id for div tag
$h2->setAttribute('data-target', '#b' . $i);
// $h2->setAttribute('data-target', '#b' . $i . ',#c' . $i);
}
}
foreach($section->getElementsByTagName('div') as $div) {
if($div->getAttribute('class') == 'divArticle') { // if this div has class divArticle
$div->setAttribute('id', 'b' . $i); // set id for div tag
}
if($div->getAttribute('class') == 'divClose') { // if this div has class maindiv
$div->setAttribute('data-target', '#b' . $i); // set id for div tag
}
}
$i++; // increment counter
}
}
// back to string again, get all contents inside body
$Content = '';
foreach($dom->getElementsByTagName('body')->item(0)->childNodes as $child) {
$Content .= $dom->saveHTML($child); // convert to string and append to the container
}
$Content = str_replace('data-target', 'data-toggle="collapse" data-target', $Content);
// $Content = str_replace('data-target', 'class="SecCon" data- toggle="collapse" data-target', $Content);
$Content = str_replace('<div class="divArticle', '<div class="divArticle collapse in article', $Content);
And this is what the HTML looks like:
<section id="introduction">
<h2 class="h2Article" id="a1" data-toggle="collapse" data- target="#b1">Introduction</h2>
<div class="divArticle collapse in article" id="b1">
The weird thing is, it works when I use the regex and DOM script BOTH, but that's going to be kind of sloppy to work with. Can anyone tell me how to modify either my regex or my DOM to make it do the job by itself?

Showing modal-box morethan 1 on a page

<< Referring to this thread >>
I want to make several modal-box on a page:
<script>
var grid_modal_options = {
height: 'auto',
width: '80%',
modal: true
};
function showProducts1ModalBox() {
$("#products1_modal_box").dialog(grid_modal_options);
$("#products1_modal_box").parent().appendTo('form:first');
}
function showProducts2ModalBox() {
$("#products2_modal_box").dialog(grid_modal_options);
$("#products2_modal_box").parent().appendTo('form:first');
}
function showProducts3ModalBox() {
$("#products3_modal_box").dialog(grid_modal_options);
$("#products3_modal_box").parent().appendTo('form:first');
}
</script>
<div id="products1_modal_box" title="Products" style="display: none;">
<div class="in">
<div class="grid-12-12">
<form id="products1_modal_box_form" action="#" method="post">
<table>
<thead>
<tr>
<th> </th>
<th>Product</th>
</tr>
</thead>
<!-- Query for read mysql goes here (I skipped this line because it's not the main thing I'm gonna ask since it's run well) /-->
<tbody>
<?php
//read the results
while($fetch = mysqli_fetch_array($r)) {
print "<tr>";
print " <td>Choose</td>";
print " <td>" . $fetch[0] . "</td>"; //$fetch[0] == Product ID
print "</tr>";
}
?>
</tbody>
</table>
</form>
</div>
</div>
</div>
<div id="products2_modal_box" title="Products" style="display: none;">
<!--
The rest goes here (the same with "products1_modal_box")
except:
print " <td>Choose</td>";
/-->
</div>
<div id="products3_modal_box" title="Products" style="display: none;">
<!--
The rest goes here (the same with "products1_modal_box")
except:
print " <td>Choose</td>";
/-->
</div>
And:
<input type='text' id='products1_id_textbox' name='products1_id_textbox' />
<a href='#' onclick='showProducts1ModalBox(); return false;'>Choose products 1</a>
<input type='text' id='products2_id_textbox' name='products2_id_textbox' />
<a href='#' onclick='showProducts2ModalBox(); return false;'>Choose products 2</a>
<input type='text' id='products3_id_textbox' name='products3_id_textbox' />
<a href='#' onclick='showProducts3ModalBox(); return false;'>Choose products 3</a>
Why this doesn't work? When I removed the div "products2_modal_box" and "products3_modal_box", the modal-box for div "products1_modal_box" appear, but when I tried to get back all of them, each modal-box doesn't appear while I clicked the link. What's wrong with the code? Thanks..
This doesn't technically answer your question, but I use jQuery Reveal for modals on my site. Seems a lot easier than what you're trying to do. Here's the source: http://www.zurb.com/playground/reveal-modal-plugin
It's really easy to set up, and you can have multiple modals per page, and can trigger them with an event (such as a click) or dynamically with jquery.
Hope this helps!

PHP remove all div with class="myclass" except first one + add another div instead of others

I have a $content with
<div class="slidesWrap">
<div class="slidesСontainer">
<div class="myclass">
...
</div>
<div class="myclass">
...
</div>
...
...
<div class="myclass">
...
</div>
</div>
<div class="nav">
...
</div>
</div>
some other text here, <p></p> bla-bla-bla
I would like to remove via PHP all the divs with class="myclass" except the first one, and add another div instead of others, so that the result is:
<div class="slidesWrap">
<div class="slidesСontainer">
<div class="myclass">
...
</div>
<div>Check all divs here</div>
</div>
<div class="nav">
...
</div>
</div>
some other text here, <p></p> bla-bla-bla
Would be grateful if someone can point me a solution.
UDATE2:
some similar question here
from that I came up with the following test code:
$content = '<div class="slidesWrap">
<div class="slidesСontainer">
<div class="myclass">
</div>
<div class="myclass">
</div>
<div class="myclass">
</div>
</div>
<div class="nav">
</div>
</div>
some other text here, <p></p> bla-bla-bla';
$dom = new DOMDocument();
$dom->loadHtml($content);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//*[#class="myClass" and position()>1]') as $liNode) {
$liNode->parentNode->removeChild($liNode);
}
echo $dom->saveXml($dom->documentElement);
Any ideas where I can test it?
Here is what you are looking for (similar to your edit, but it removes the added html tags):
$doc = new DOMDocument();
$doc->loadHTML($content);
$xp = new DOMXpath($doc);
$elements = $xp->query("//div[#class='myclass']");
if($elements->length > 1)
{
$newElem = $doc->createElement("div");
$newElem->appendChild($doc->createTextNode("Check all divs "));
$newElemLink = $newElem->appendChild($doc->createElement("a"));
$newElemLink->setAttribute("href", "myurl");
$newElemLink->appendChild($doc->createTextNode("here"));
$elements->item(1)->parentNode->replaceChild($newElem, $elements->item(1));
for($i = $elements->length - 1; $i > 1 ; $i--)
{
$elements->item($i)->parentNode->removeChild($elements->item($i));
}
}
echo $doc->saveXML($doc->getElementsByTagName('div')->item(0));
$var = ':not(.myClass:eq(1))';
$var.removeClass("myClass");
$var.addClass("some_other_Class");
If I got you right, you've got a string called $content with all that content in it
It's not the best solution I guess but here is my attempt (which works fine for me):
if( substr_count($content, '<div class="myclass') > 1 ) {
$parts = explode('<div class="myclass',$content);
echo '<div class="myclass'.$parts[1];
echo '<div>Check all divs here</div>';
}
else {echo $content;}

Parse span class text with DOM PHP

I've been having an issue trying to parse text in a span class with DOM. Here is my code example.
$remote = "http://website.com/";
$doc = new DOMDocument();
#$doc->loadHTMLFile($remote);
$xpath = new DOMXpath($doc);
$node = $xpath->query('//span[#class="user"]');
echo $node;
and this returns the following error -> "Catchable fatal error: Object of class DOMNodeList could not be converted to string". I am so lost I NEED HELP!!!
What I am trying to do is parse the user name between this span tag.
<span class="user">bballgod093</span>
Here is the full source from the remote website.
<div id="randomwinner">
<div id="rndmLeftCont">
<h2 id="rndmTitle">Hourly Random <span>Winner</span></h2>
</div>
<div id="rndmRightCont">
<div id="rndmClaimImg">
<table cellspacing="0" cellpadding="0" width="200">
<tbody>
<tr>
<td align="right" valign="middle">
</td>
</tr>
</tbody>
</table>
</div>
<div id="rndmCaimTop">
<span class="user">bballgod093</span>You've won 1000 SB</div>
<div id="rndmCaimBottom">
<a id="rndmCaimBtn" class="btn1 btn2" href="/?cmd=cp-claim-random" rel="nofollow">Claim Bucks</a>
</div>
</div>
<div class="clear"></div>
</div>
This call
$node = $xpath->query('//span[#class="user"]');
does not return a string, but a DOMNodeList.
You can use this list somewhat like array (using $node->length for the number of elements and $node->item(0) to get the first element) to get DOMNode objects. Each of these objects has a nodeValue property which is a string.
So you would do something like
$node = $xpath->query('//span[#class="user"]');
if($node->length != 1) {
// error?
}
echo $node->item(0)->nodeValue;
Of course, changing the variable name for $node to something more appropriate would be nice.

Categories