2012-09-04 5 views
0

내가 액세스 한 특정 노드의 자식 노드를 가져와야합니다 (클래스 = 제목이있는 li 노드)PHP에서 노드의 자식 노드를 얻는 방법?

어떻게 도와 줄 수 있습니까?

<?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; 

    ?> 
+0

을하고 작동하지 않습니다? –

+1

BTW :'DOMDocument'는'loadHTMLFile()'함수를 가지고 있으므로 CURL을 사용할 필요가 없습니다 : http://php.net/domdocument.loadhtmlfile.php – feeela

답변

0

당신은, 예를 들어, 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); 
    } 
} 
관련 문제