如何仅打印一个带有卷曲的标签 [英] how to print only one tag with curl

查看:96
本文介绍了如何仅打印一个带有卷曲的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网络中有2或3个标签< p> ,但我只想打印第一和第二个< p>

i have 2 or 3 tag <p> in my web but, im just want to print first and second <p>.

我该怎么做?

这里是我的代码

<?php
$url = "http://www.web.org/dorama/1401143633/momikeshite-fuyu--wagaya-no-mondai-nakatta-koto-ni";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);
$dom = new DOMDocument();
@$dom->loadHTML($html);

foreach($dom->getElementsByTagName('p') as $link) {
        echo $dom->saveXML( $link);
}
?>


推荐答案

使用 getElementsByTagName( ),您会获得一个节点列表(DOMNodeList),当前您使用 foreach()遍历所有节点。如果只想要第一个,则可以使用 item()来获取想要的特定对象(本例中为0)...

When you use getElementsByTagName() you get a list of nodes ( DOMNodeList ) which you currently use foreach() to iterate over all of them. If you just want the first, you can use item() to fetch the particular one you want (0 in this case)...

echo $dom->saveXML( $dom->getElementsByTagName('p')->item(0) );

这篇关于如何仅打印一个带有卷曲的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆