dousi8237 2010-09-30 15:18
浏览 42
已采纳

如何编写preg_match_all只是为了获取一个特定的元素?

Until the website give me an access to his API, i need to display only 2 things from this website :

What i want to grab // Example on a live page

Those 2 things are contained in a div :

<div style="float: right; margin: 10px;">
here what i want to display on my website
</div>

The problem is that i found an example on stackoverflow, but i never wrote preg_match before. How to do this with the data i want to grabb ? Thank you

<?php   $html = file_get_contents($st_player_cv->getUrlEsl());

preg_match_all(
    'What do i need to write here ?',
    $html,
    $posts, // will contain the data
    PREG_SET_ORDER // formats data into an array of posts
);

foreach ($posts as $post) {
    $premium = $post[1];
    $level = $post[2];

    // do something with data
}
  • 写回答

3条回答 默认 最新

  • duanchao1002 2010-09-30 15:42
    关注

    The DOM way to do it would be

    libxml_use_internal_errors(TRUE);
    $dom = new DOMDocument;
    $dom->loadHTMLFile('http://www.esl.eu/fr/player/5178309/');
    libxml_clear_errors();
    
    $xPath = new DOMXPath($dom);
    $nodes = $xPath->query('//div[@style="float: right; margin: 10px;"]');
    foreach($nodes as $node) {
        echo $node->nodeValue, PHP_EOL;
    }
    

    but there is a whole slew of JavaScript in the page that modifies the DOM heavily after the page was loaded. Since any PHP script based fetching will not execute any JavaScript, the style we search for in the XPath does not exist yet and we won't get any results (the Regex suggesed by Hannes doesn't work for the same reason). Neither do the level numbers on the badge exist yet.

    As Wrikken pointed out in the comments, there also seems to be some mechanism to block certain requests. I had the message once, but I am not sure what triggers it, because I could also fetch page on several occasions.

    To cut a long story short: you cannot achieve what you are trying to do with this page.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序