简体   繁体   中英

how to get child nodes of the node in php?

I need to get the child nodes of the particular nod that i have accessed(li node with class = title )

please help me how do i do that?

    <?php
    $options = array(
    CURLOPT_RETURNTRANSFER => true,     // return web page
    CURLOPT_HEADER         => false,    // don't return headers
    CURLOPT_FOLLOWLOCATION => true,     // follow redirects
    CURLOPT_ENCODING       => "",       // handle all encodings
    CURLOPT_USERAGENT      => "SomeUcam v0.1 Bot", // who am i
    CURLOPT_AUTOREFERER    => true,     // set referer on redirect
    CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
    CURLOPT_TIMEOUT        => 120,      // timeout on response
    CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
       );

        $ch      = curl_init( "http://example.com/?page=1" );
       curl_setopt_array( $ch, $options );
       $content = curl_exec( $ch );
       $err     = curl_errno( $ch );
       $errmsg  = curl_error( $ch );
       $header  = curl_getinfo( $ch );
       curl_close( $ch );

    $newDom = new domDocument;
    $newDom->loadHTML($content);

    $finder = new DomXPath($newDom);
    $classname="title";
    $nodes = $finder->query("//*[contains(@class, '$classname')]");
    $nodesNo = $nodes->length;
    echo $nodesNo;

    ?>

You could, for example, iterate over the nodes using a foreach -loop:

$url = 'http://example.com/';

/* this is necessary to prevent DOMDocument errors on HTML5-elements */
libxml_use_internal_errors( true );

$dom = new DOMDocument();
$dom->loadHTMLFile( $url );
$finder = new DOMXpath( $dom );
$nodes = $finder->query( "//*[contains(@class, 'title')]" );

if( $nodes instanceof DOMNodeList )
{
    foreach( $nodes as $node )
    {
        var_dump( $node->nodeName, $node->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