简体   繁体   中英

I have the javascript code getElementsByClassName how it will be on php?

i have this code on javascript

String(document.getElementsByClassName('ord-total-val')[0].innerText).substr(0,3)

this cod grab class element 'ord-total-val', and returns its text string to me. I try this:

$classname="blockProduct";
$finder = new DomXPath($doc);
$spaner = $finder->query("//*[contains(@class, '$classname')]");

But my knowledge is not enough to complete it. Can you help my to write this stroke on php?

To be fair your code is virtually complete and appears to work OK when I combined it with a basic test case.

<?php


    $strhtml="<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <style></style>
        <script></script>
    </head>
    <body>
        <p>wibble wobble</p>
        <div class='blockProduct'>whoohoo! Some text</div>
        <p>lorem ipsum dolor solit...</p>
        <span class='blockProduct'>and even more text in a different HTML element</span>
    </body>
</html>";


    $className='blockProduct';


    $dom=new DOMDocument;
    $dom->loadHTML($strhtml);
    
    $xp=new DOMXPath($dom);
    $expr='//*[ contains( @class, "'.$className.'" ) ]';
    
    $col=$xp->query( $expr );
    if( $col && $col->length > 0 ){
        foreach( $col as $node ){
            $text=$node->nodeValue;
            $substr=substr($text,0,3);
            
            echo $substr . '<br />';
        }
    }
?>

Given the HTML source above this will output:

who
and

Using your code, but modified just slightly to use the XPath object already created, $xp :

$spaner = $xp->query("//*[contains(@class, '$className')]");

This gives a nodelist so you need to iterate through this nodelist to show the contents.

foreach($spaner as $span)echo $span->nodeValue;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM