繁体   English   中英

如何过滤结果? HTML Dom解析器

[英]How do I filter my results ? Html Dom Parser

我得到以下代码:

<?php
    include('simple_html_dom.php');
    $html = file_get_html('http://www.google.com/search?q=BA236',false);
    $e = $html->find("div[class=g]");
echo $e[0]->innertext;
?>

当我运行它时,我得到了谷歌搜索结果的第一类,它是:

British Airways Flight 236

Scheduled   departs in 13 hours 13 mins

Departure   DME 5:40 AM     —

Moscow  Dec 15

Arrival LHR 6:55 AM     Terminal 5

London  Dec 15

Scheduled   departs in 1 day 13 hours

Departure   DME 5:40 AM     —

Moscow  Dec 16

Arrival LHR 6:55 AM     Terminal 5

London  Dec 16

我的问题是我不需要所有这些信息,而且我不知道如何过滤此回声,因为HTML代码没有id或类。 我考虑过用jQuery或简单的CSS隐藏不需要的html,但是:同样的问题,我没有id或类来调用它们。

因此,我该如何过滤掉我不想要的信息。 请给我看一个例子,我将检查需要删除自己的html。 谢谢。

您要搜索的内容称为grep工具(或正则表达式)。 请参阅SO网站的PHP,以在txt文件中进行搜索,并在整行中回显可能的答案。 稍微修改到您的应用程序:

$contents = 'British Airways Flight 236\n\nScheduled   departs in 13 hours 13 mins\n\nDeparture   DME 5:40 AM     —\n\Moscow  Dec 15\n\n...'

$searchfor = 'departs';

$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if (preg_match_all($pattern, $contents, $matches)) {
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
} else {
   echo "No matches found";
}

编辑:

或者,如注释中所述,使用->saveHTML而不是->innertext保留HTML结构,以便于解析。

我怎么找到最后一个<div class>在带有 PHP 简单 HTML DOM 解析器的 HTML 文件中?</div><div id="text_translate"><p> 根据<a href="http://simplehtmldom.sourceforge.net/" rel="nofollow noreferrer">SIMPLE HTML DOM PARSER</a>的文档(在“How to modify HTML Elements”选项卡下),这段代码找到了<div class="hello">的第一个实例:</p><pre> $html = str_get_html('<div class="hello">Hello</div><div class="world">World</div>'); $html->find('div[class=hello]', 0)->innertext = 'foo'; echo $html; // Output: <div class="hello">foo</div><div class="world">World</div></pre><p> 如果我想在<div class="hello">的<em>最后一个</em>实例中插入 'foo' 怎么办,假设 HTML 代码有很多<div class="hello">实例。</p><p> 什么应该取代0 ?</p></div>

[英]How do I find the last <div class> in an HTML File with PHP Simple HTML DOM Parser?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM