dream_high1026 2015-10-20 15:19
浏览 24
已采纳

PHP获取html的某些部分

I tried to get the src of an iframe inside of an html using this

preg_match('/src=\'([^\']+)\'/', $fresult, $match);

but this code sometimes fails.

some sugest that I use an DomDocument But I can't found a reg exp sample

$doc = new DOMDocument();
$doc->loadHTML($html); 
foreach ($tags as $tag) {
    echo $tag->nodeValue;
}

How do I get the src value of frame?

sample

<iframe src='test.com' />

i should have test.com

also how do I do the preg_match_all equivalent of DomDocument?

like this

<html>
<label class="su">test1</label>
<label class="su">test2</label>
<label class="su">test3</label>
</html>

which is I should have a array result for test1, test2 and test3

I am new to this dom php thing. so please don't be harsh. thanks

  • 写回答

1条回答 默认 最新

  • dry0106 2015-10-20 15:31
    关注

    First of all, welcome to Stack Overflow! Please do not use regular expressions on DOM documents (see here why). Instead, please stick to PHP DomDocument.

    That said, you may get an iframe tag and src like so:

    $doc = new DOMDocument();
    $doc->loadHTML(...); 
    $frame= $doc->getElementsByTagName('iframe')->item(0);
    $src = $frame->getAttribute('src');
    

    Concerning your second question, you might want to have a look at DOMXPath:

    $doc = new DOMDocument();
    $doc->loadHTMLFile(...);
    
    $xp = new DOMXPath($dom);
    $labels = $xp->query('//label[@class="su"]');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应