I'm not sure what I'm doing wrong but I'm getting the right nodeValue for what I want. It's just not updating when the php script is done. Here's the code:
$dom = new DOMDocument();
//suppress HTML5 and other errors
libxml_use_internal_errors(true);
$dom->loadHTMLFile($pageURL);
libxml_use_internal_errors(false);
$xpath = new DOMXPath($dom);
$divContent = $xpath->query("//*[#id='resultStats']/p")->item(0);
$newText = new DOMText("100 results");
var_dump($divContent->nodeValue); //returns old test value "400 results" which is correct
$divContent->removeChild($divContent->firstChild);
$divContent->appendChild($newText);
var_dump($divContent->localName); //"p" because i got it from <p> in resultStats
var_dump($divContent->textContent); //"100 results"
var_dump($divContent->nodeValue); //"100 results"
more of the HTML that is around it
<div class="container">
<div class="row">
<div class="resultStats span3 offset1" id="resultStats">
<p>400 results found.</p>
</div>
</div>
<div class="row">
<div class="span12">
<div class="row">
<div class="span6 offset1">
<?php
if (isset($_POST['q'])) {
//code from above that is executing every time from tests
}
?>
</div>
<div class="span5">
span5
</div>
</div>
</div>
</div>
I'm not sure what I'm doing wrong. If I do dom->save it rewrites everything (even php code) so I don't think that's a good idea.
I don't understand why you're using DOMDocument for this. Can't you just do this:
<div class="container">
<div class="row">
<div class="resultStats span3 offset1" id="resultStats">
<?php
// get new result count somehow in $resultCount
echo '<p>'.$resultCount.' results found</p>';
?>
</div>
</div>
Related
I would like to know if there is any way, in php, to match all classes with the same word,
Example:
<div class="classeby_class">
<div class="classos-nope">
<div class="row">
<div class="class-show"></div>
</div>
</div>
</div>
<div class="class-first-one">
<div class="container">
<div class="classes-show">
<div class="class"></div>
<div class="classing"></div>
</div>
</div>
</div>
in the example above I would like to match all div that contain the word "class" but do not match those that have the word "classes"
like,
positive for
<div class="class-show">...</div>
<div class="class-first-one">...</div>
<div class="class">...</div>
<div class="class-first-one">...</div>
but negative for
<div class="classeby_class">...</div>
<div class="classes-show">...</div>
<div class="classing">...</div>
I am using php to display several different html pages.
As regex would not be the appropriate method, first because of several page breaks, second because of hosting limitations, I'm trying to do this by parse.
All html code is stored on the server.
I can liminate with a specific class using the example below.
$doc = new DomDocument();
$xpath = new DOMXPath($doc);
$classtoremove = $xpath->query('//div[contains(#class,"class")]');
foreach($classtoremove as $classremoved){
$classremoved->parentNode->removeChild($classremoved);
}
echo $HTMLDoc->saveHTML();
I know there are CSS selectors, but when I try to use it in PHP it doesn't work. Possibly because I'm using XPath.
Example:
'[id*="class"],[class*="class"]'
Still, I think he would take values beyond what I need.
Any way to get these values by Xpath?
the intent is to completely remove the div or other tags that contain that word.
You could make use of a regex with word boundaries \bclass\b for the class attribtute and make use of DOMXPath::registerPhpFunctions.
For example
$data = <<<DATA
<div class="classeby_class">
<div class="classos-nope">
<div class="row">
<div class="class-show"></div>
</div>
</div>
</div>
<div class="class-first-one">
<div class="container">
<div class="classes-show">
<div class="class"></div>
<div class="classing"></div>
</div>
</div>
</div>
DATA;
$doc = new DomDocument();
$doc->loadHTML($data);
$xpath = new DOMXPath($doc);
$xpath->registerNamespace("php", "http://php.net/xpath");
$xpath->registerPHPFunctions();
$classtoremove = $xpath->query("//div[1 = php:function('preg_match', '/\bclass\b/', string(#class))]");
foreach ($classtoremove as $a) {
var_dump($a->getAttribute("class"));
}
Output
string(10) "class-show"
string(15) "class-first-one"
string(5) "class"
See a PHP demo
I inherited the following piece of PHP code, that removes elements from the DOM before pushing the content into a page. We only want to show the first 5 elements to not have a too long page
Assuming the code retrieves an HTML fragment structured like this:
<div class='year'>2019</div>
<div class='record'>Record A</div>
<div class='record'>Record B</div>
<div class='year'>2018</div>
<div class='record'>Record C</div>
<div class='record'>Record D</div>
<div class='record'>Record E</div>
<div class='year'>2017</div>
<div class='record'>Record F</div>
<div class='year'>2016</div>
<div class='record'>Record G</div>
Now, the below piece of code removes all the extra records:
$dom = new DOMDocument();
// be sure to load the encoding
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $tmp);
// let's use XPath
$finder = new DomXPath($dom);
// set the limit
$limit = 5; $cnt = 0;
// and remove unwanted elements
foreach($finder->query("//*[contains(#class, 'record')]") as $elm ) {
if ($cnt >= $limit)
$elm->parentNode->removeChild($elm);
$cnt++;
}
// finally, echo
echo $dom->saveHTML($dom->documentElement);
Logically, I end up having the following HTML:
<div class='year'>2019</div>
<div class='record'>Record A</div>
<div class='record'>Record B</div>
<div class='year'>2018</div>
<div class='record'>Record C</div>
<div class='record'>Record D</div>
<div class='record'>Record E</div>
<div class='year'>2017</div>
<div class='year'>2016</div>
How could I identify all the elements having the class year and having the next sibling also having this class and delete it? (here that would get the 2017 element)
Then I believe it would only be a matter of checking if the last element has the class year and remove it.
Or is there a cleaner way to achieve that?
You can add an extra foreach after the current one...
foreach($finder->query("//div[#class='year']/following-sibling::div[1][#class='year']")
as $elm ) {
$elm->parentNode->removeChild($elm);
}
The XPath here is looking for a <div class="year"> element and then only looking at the next <div> tag for the same thing (following-sibling::div[1] limits it to just the next div tag after the current one).
Here is a plain JS method in case you want to do this on the client instead
const recs = document.querySelectorAll(".record");
const divs = document.querySelectorAll("div");
const lastRec = recs[4];
let found = false;
divs.forEach(div => {
div.classList.toggle("hide",found)
if (div === lastRec) found = true
})
.hide { display:none}
<div class='year'>2019</div>
<div class='record'>Record A</div>
<div class='record'>Record B</div>
<div class='year'>2018</div>
<div class='record'>Record C</div>
<div class='record'>Record D</div>
<div class='record'>Record E</div>
<div class='year'>2017</div>
<div class='record'>Record F</div>
<div class='year'>2016</div>
<div class='record'>Record G</div>
I finally ended up using the following code:
$dom = new DOMDocument();
// be sure to load the encoding
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $tmp);
// let's use XPath
$finder = new DomXPath($dom);
foreach($finder->query("(//*[contains(#class, 'record')])[5]/following-sibling::*") as $elm) {
$elm->parentNode->removeChild($elm);
}
// finally, echo
echo $dom->saveHTML($dom->documentElement);
it allowed me to achieve my goal in 1 pass without using nested loops
I have this html structure:
<div class="wanted-list">
<div class="headline"></div>
<div class="entry">
<div></div>
<div></div>
<div class="length">1100</div>
<div></div>
<div class="status">
<img src="xxxx" alt="open">
</div>
</div>
<div class="entry mark">
<div></div>
<div></div>
<div class="length">800</div>
<div></div>
<div class="status">
<img src="xxxx" alt="open">
</div>
</div>
<div class="entry">
<div></div>
<div></div>
<div class="length">2300</div>
<div></div>
<div class="status">
<img src="xxxx" alt="closed">
</div>
</div>
</div>
I want to select only the items that are 'open', so I do:
$doc4 = new DOMDocument();
$doc4->loadHtmlFile('http://www.whatever.com');
$doc4->preserveWhiteSpace = false;
$xpath4 = new DOMXPath($doc4);
$elements4 = $xpath4->query("//div[#class='wanted-list']/div/div[5]/img[#alt='open']");
Now, if I'm not mistaken, we have isolated the 'open' items we wanted. Now, I need to get the 'length' values, and sum them to make a total length so I can echo it. I've spent several hours trying different solutions and researching, but I haven't found anything similar. Can you guys help?
Thanks in advance.
EDITED the wrong div's, sorry.
I'm not sure if you mean for the calculations all to be done in the xsl or whether you are just wanting the sum of the lengths to be available to you in php, however this captures and sums the lengths. As noted by #Chris85 in the comment - the html is invalid - there are spare closing div tags within each entry ~ presumably the image is supposed to be a child of div.status? If that is so the below would need slight modification when trying to target the correct parent. That said, I received no warnings from DOMDocument whilst parsing it but better to fix than ignore!
$strhtml='
<div class="wanted-list">
<div class="headline"></div>
<div class="entry">
<div></div>
<div></div>
<div class="length">1100</div>
<div></div>
<div class="status">
<img src="xxxx" alt="open">
</div>
</div>
<div class="entry mark">
<div></div>
<div></div>
<div class="length">800</div>
<div></div>
<div class="status">
<img src="xxxx" alt="open">
</div>
</div>
<div class="entry">
<div></div>
<div></div>
<div class="length">2300</div>
<div></div>
<div class="status">
<img src="xxxx" alt="closed">
</div>
</div>
</div>';
$dom = new DOMDocument();
$dom->loadHtml( $strhtml );/* alternative to loading a file directly */
$dom->preserveWhiteSpace = false;
$xp = new DOMXPath($dom);
$col=$xp->query('//img[#alt="open"]');/* target the nodes with the attribute you need to look for */
/* variable to increment with values found from DOM values */
$length=0;
foreach( $col as $n ) {/* loop through the found nodes collection */
$parent=$n->parentNode->parentNode;/* corrected here to account for change in html layout ~ get the suitable parent node */
/* based on original code, find value from particular node */
$length += $parent->childNodes->item(5)->nodeValue;
}
echo 'Length:'.$length;
I am having some trouble trying to loop through an XML document. The XML looks like this:
<data>
<weather>
<hourly>
<time>0</time>
<tempC>17</tempC>
<tempF>62</tempF>
<windspeedMiles>24</windspeedMiles>
<windspeedKmph>39</windspeedKmph>
</hourly>
<hourly>
<time>3</time>
<tempC>16</tempC>
<tempF>60</tempF>
<windspeedMiles>22</windspeedMiles>
<windspeedKmph>35</windspeedKmph>
</hourly>
</weather>
<weather>
<hourly>
<time>0</time>
<tempC>17</tempC>
<tempF>62</tempF>
<windspeedMiles>24</windspeedMiles>
<windspeedKmph>39</windspeedKmph>
</hourly>
<hourly>
<time>3</time>
<tempC>16</tempC>
<tempF>60</tempF>
<windspeedMiles>22</windspeedMiles>
<windspeedKmph>35</windspeedKmph>
</hourly>
</weather>
</data>
My code (below) whilst it loops through all 'weather' nodes, it only picks out the first 'hourly' child node and completely skips the second. Would someone be able to help me as if I am honest, I do not know enough about looping to fix it and its driving me nuts! Grr.
Here is my PHP code which loads an XML document from online and then formats the XML results into div tags and obviously loops through the XML but as I said only loops through the first 'hourly' node of each 'weather' node.
<?php
// load SimpleXML
$data = new SimpleXMLElement('myOnlineXMLdocument.xml', null, true);
echo <<<EOF
<div class="observationRow">
<div class="observationTitleSmall"><br>Time</div>
<div class="observationTitleSmall"><br>Temp C</div>
<div class="observationTitleSmall"><br>Temp F</div>
<div class="observationTitleSmall"><br>Wind Speed MPH</div>
<div class="observationTitleSmall"><br>Wind Speed KMPH</div>
</div>
EOF;
foreach($data as $weather) // loop through our hours
{
echo <<<EOF
<div>
<div class="observationCellSmall"><br>{$weather->time}</div>
<div class="observationCellSmall"><br>{$weather->tempC}</div>
<div class="observationCellSmall"><br>{$weather->tempF}</div>
<div class="observationCellSmall"><br>{$weather->hourly->windspeedMiles}</div>
<div class="observationCellSmall"><br>{$weather->hourly->windspeedKmph}</div>
EOF;
}
echo '</div>';
?>
EDITED CODE:
$str = "";
foreach($data->weather as $weather)
{
foreach ($weather->hourly as $hour)
{
$str .= "
<div>";
if ($hour->time == "0") {
$str .= "
<div class='observationCellSmall'><br>$weather->date</div>
<div class='observationCellSmall'><br>$weather->maxtempC</div>
<div class='observationCellSmall'><br>$weather->mintempC</div>";
}
$str .= "
<div class='observationCellSmall'><br>$hour->time</div>
<div class='observationCellSmall'><br>$hour->tempC</div>
<div class='observationCellSmall'><br>$hour->tempF</div>
<div class='observationCellSmall'><br>$hour->windspeedMiles</div>
<div class='observationCellSmall'><br>$hour->windspeedKmph</div>
</div>
";
}
}
echo $str;
Using a slenderized version of your XML feed, that generates this:
<div>
<div class='observationCellSmall'><br>2013-08-19</div>
<div class='observationCellSmall'><br>17</div>
<div class='observationCellSmall'><br>15</div>
<div class='observationCellSmall'><br>0</div>
<div class='observationCellSmall'><br>15</div>
<div class='observationCellSmall'><br>59</div>
<div class='observationCellSmall'><br>11</div>
<div class='observationCellSmall'><br>18</div>
</div>
<div>
<div class='observationCellSmall'><br>300</div>
<div class='observationCellSmall'><br>15</div>
<div class='observationCellSmall'><br>59</div>
<div class='observationCellSmall'><br>13</div>
<div class='observationCellSmall'><br>21</div>
</div>
<div>
<div class='observationCellSmall'><br>2013-08-20</div>
<div class='observationCellSmall'><br>21</div>
<div class='observationCellSmall'><br>16</div>
<div class='observationCellSmall'><br>0</div>
<div class='observationCellSmall'><br>17</div>
<div class='observationCellSmall'><br>62</div>
<div class='observationCellSmall'><br>11</div>
<div class='observationCellSmall'><br>18</div>
</div>
<div>
<div class='observationCellSmall'><br>300</div>
<div class='observationCellSmall'><br>16</div>
<div class='observationCellSmall'><br>61</div>
<div class='observationCellSmall'><br>10</div>
<div class='observationCellSmall'><br>17</div>
</div>
You need a nested loop. One to loop over the weathers, and and another to loop over the hourlies.
foreach($data->weather as $weather) {
foreach($weather->hourly as $hourly) {
// code here
}
}
I don't remember the simplexml API 100% off my head, if that doesn't work you might need to use ->getChildren() or something to make it iterable.
Either that, or use xpath and nab the hourlies directly: /data/weather/hourly.
I have the following HTML:
[...]
<div class="row clearfix">
<div class="col1">Data</div>
<div class="col2">Data</div>
<div class="col3">Data</div>
<div class="col4">Data</div>
<div class="col5">Data</div>
<div class="col6">Data</div>
<div class="col7">Data</div>
<div class="col8">Data</div>
</div><!--// row-->
<div class="row clearfix otherClass">
<div class="col1">Data</div>
<div class="col2">Data</div>
<div class="col3">Data</div>
<div class="col4">Data</div>
<div class="col5">Data</div>
<div class="col6">Data</div>
<div class="col7">Data</div>
<div class="col8">Data</div>
</div><!--// row-->
<div class="row clearfix thirdClass">
<div class="col1">Data</div>
<div class="col2">Data</div>
<div class="col3">Data</div>
<div class="col4">Data</div>
<div class="col5">Data</div>
<div class="col6">Data</div>
<div class="col7">Data</div>
<div class="col8">Data</div>
</div><!--// row-->
[...]
I want to get all of these divs out of the HTML, they all start with "row clearfix" as class, but can have more data to it.
After that I want to be able to handle each col separetely, so get the value of col1, col2, col3 ect.
I have written this code, but am stuck now. Can someone help me out?
$oDom = new DOMDocument();
$oDom->loadHtml($a_sHTML);
$oDomXpath = new DOMXpath($oDom);
$oDomObject = $oDomXpath->query('//div[#class="row clearfix"]');
foreach ($oDomObject as $oObject) {
var_dump($oObject->query('//div[#class="col1"]')->nodeValue);
}
UPDATE *Solution*
Thanks to the replies below, I got it working with the following code:
$oDom = new DOMDocument();
#$oDom->loadHtml($a_sHTML);
$oDomXpath = new DOMXpath($oDom);
$oDomObject = $oDomXpath->query('//div[contains(#class,"row") and contains(#class,"clearfix")]');
foreach ($oDomObject as $oObject) {
foreach($oObject->childNodes as $col)
{
if ($col->hasAttributes())
{
var_dump($col->getAttribute('class') . " == " . trim($col->nodeValue));
}
}
}
To match the outer divs I think that what you need is
//div[starts-with(#class,"row clearfix")]
or
//div[contains(#class,"row clearfix")]
or
//div[contains(#class,"row") and contains(#class,"clearfix")]
I'd go for the last one because the class names could be in any order.
I am not 100% sure what you want to do with the inner div, but you could get them with something like this:
div[starts-with(#class,"col")]