【问题标题】:How to parse multiple elements in portions for html via Simple Html Dom如何通过简单的 Html Dom 为 html 解析多个元素
【发布时间】:2015-08-07 12:33:24
【问题描述】:

我正在尝试在 li 中获取各种元素,如下所示。我对此很陌生,所以我可能没有使用最有效的方法,但这是我开始的地方......

简化的示例代码....

<li id='entry_0' title='09879879'>
    <div ....>
        <h2> The title text would go here </h2>
        <span class='entrySize' ....> 20oz </span>
        <span class='entryPrice' ....> $32.09 </span>
        <span class='anotherEntry' ....> More Data I need To Grab </span>
        .......
    </div>
</li>

<li> .... With same structure as above .... 100's of entries like this </li>

我知道如何单独提取各个部分,但无法掌握如何在 html 的一部分中进行分组。

$filename = "directory/file.html";
$html = file_get_html($filename);

for($i=0; $i<=count(entryNumber);$i++)
{
    $li_id = "entry_".$i;
    foreach($html->find('li[id='.$li_id.']') as $li) {         
        echo $li->innertext;
    }
}

所以这让我得到了带有 id 号作为唯一属性的行项目标签中的内容。我想在遍历订单项标签时获取 h2 文本、entrySize、entryPrice 等。我不明白的是,一旦我有了订单项标签内容,我该如何解析该订单项的内部标签和属性。整个 HTML 文档的其他部分可能具有与整个文档相同的 id、类标签,因此我将其分解为多个部分,而不是一次解析每个部分。

我还想从 li 标签的 title 标签中提取 title 属性。

我希望我的解释有意义。

【问题讨论】:

  • 我正在测试一些代码并通过添加..... echo $li->title 我能够从中获取标题值。仍在处理订单项标签中的其他元素/标签。

标签: php html parsing dom


【解决方案1】:

您可能应该使用 DOM 解析器。 PHP 与其中一个捆绑在一起,您可以使用许多其他的。

http://php.net/dom

PHP Simple HTML DOM Parser

<?php
$html = file_get_content($page);
$doc = new DOMDocument();
$doc->loadHTML($html);

// now find what you need
$items = $dom->getElementsByTagName('li');
foreach ($items as $item) {
    $id = $item->getAttribute('id');
    if (strpos($id, 'item_') !== false) {
        // found matchin li, grab its children
    }
}

以此为基准,我们无法为您编写所有代码。查看 PHP 文档以完成此操作 :) 根据我目前的情况,您需要遵循文档以使其获取子值并处理它们。

【讨论】:

  • 感谢您的信息。很有帮助。
猜你喜欢
  • 2012-08-28
  • 2012-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多