用 php 只回显一个 div

发布于 2024-10-15 18:44:11 字数 312 浏览 4 评论 0原文

我正在尝试制作一个脚本,仅回显包含 google 图像的 div。

$url = "http://www.google.com/";
$page = file($url);

foreach($page as $theArray) {
echo $theArray;
}

问题是这会回显整个页面。 我只想回显

和下一个最接近的
之间的部分 注意:我尝试过使用 if,但它不起作用,所以我删除了它们,

谢谢

I'm attempting to make a script that only echos the div that encolose the image on google.

$url = "http://www.google.com/";
$page = file($url);

foreach($page as $theArray) {
echo $theArray;
}

The problem is this echos the whole page.
I want to echo only the part between the <div id="lga"> and the next closest </div>
Note: I have tried using if's but it wasn't working so I deleted them

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

檐上三寸雪 2024-10-22 18:44:11

使用内置 DOM 方法:

<?php

$page = file_get_contents("http://www.google.com");

$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML($page);
libxml_use_internal_errors(false);

$domx = new DOMXPath($domd);
$lga = $domx->query("//*[@id='lga']")->item(0);

$domd2 = new DOMDocument();
$domd2->appendChild($domd2->importNode($lga, true));

echo $domd2->saveHTML();

Use the built-in DOM methods:

<?php

$page = file_get_contents("http://www.google.com");

$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML($page);
libxml_use_internal_errors(false);

$domx = new DOMXPath($domd);
$lga = $domx->query("//*[@id='lga']")->item(0);

$domd2 = new DOMDocument();
$domd2->appendChild($domd2->importNode($lga, true));

echo $domd2->saveHTML();
夏见 2024-10-22 18:44:11

为此,您需要解析 DOM,然后获取您要查找的 ID。查看像这样的解析库 http://simplehtmldom.sourceforge.net/manual.htm

之后将您的 html 文档输入解析器,您可以这样称呼:

$html = str_get_html($page); 
$element = $html->find('div[id=lga]'); 
echo $element->plaintext;

我认为,这将是您最快和最简单的解决方案。

In order to do this you need to parse the DOM and then get the ID you are looking for. Check out a parsing library like this http://simplehtmldom.sourceforge.net/manual.htm

After feeding your html document into the parser you could call something like:

$html = str_get_html($page); 
$element = $html->find('div[id=lga]'); 
echo $element->plaintext;

That, I think, would be your quickest and easiest solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文