duangong937906 2014-05-19 09:27
浏览 72
已采纳

解析dom xpath什么都不做

I want to get all the links on a page so I could get attributes like title of the a href etc...

<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "
";
}

set_exception_handler('exception_handler');

function dom_create()
{
  echo("domcreate");
  $file = file_get_html('http://www.facebook.com/plugins/fan.php?connections=100&id=40796308305');
  echo($file);
  $doc = new DOMDocument();
  $doc->loadHTMLFile($file);

  $xpath = new DOMXpath($doc);

  $elements = $xpath->query("//*[@id]");


  if (!is_null($elements)) {
    foreach($elements as $e){
      $documentLinks = $e->getElementsByTagName('a');
    }
    else
      echo "NULL";
  }
}

dom_create();
?>

I don't get any output even if I just set echo statements. Anyone an idea?

  • 写回答

2条回答 默认 最新

  • duandingqi9442 2014-05-19 10:02
    关注

    I solved it by doing it via get_contents and give it a context.

    <?php
    function exception_handler($exception) {
      echo "Uncaught exception: " , $exception->getMessage(), "
    ";
    }
    
    set_exception_handler('exception_handler');
    
    function dom_create()
    {
      $context = stream_context_create(array('http' => array('header' => 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0')));
      $file = file_get_contents('http://www.facebook.com/plugins/fan.php?connections=100&id=6568341043637',false, $context);
      $dom = new DOMDocument;
      $dom->loadHTML($file);
      foreach ($dom->getElementsByTagName('a') as $node) {
        echo $dom->saveHtml($node), PHP_EOL;
      }
    }
    
    dom_create();
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog