PHP:简单的HTML DOM解析器 - 如何获取具有特定内容的元素


PHP: Simple HTML DOM Parser - how to get the element which has certain content?

在PHP中,我使用的是Simple HTML DOM Parser class。

我有一个包含多个 A 标签的 HTML 文件。

现在我需要找到里面有特定文本的标签。

例如:

$html = "<a id='tag1'>A</a>
         <a id='tag2'>B</a>
         <a id='tag3'>C</a>
        ";
$dom = str_get_html($html);
$tag = $dom->find("a[plaintext=B]");

上面的示例不起作用,因为纯文本只能用作属性。

有什么想法吗?

<?php
include("simple_html_dom.php");
$html = "<a id='tag1'>A</a>
         <a id='tag2'>B</a>
         <a id='tag3'>C</a>
        ";
$dom = str_get_html($html);
$select = NULL;
foreach($dom->find('a') as $element) {
       if ($element->innertext === "B") {
            $select = $element;
            break;   
       }
}
?>

假设您要查找的每个特定文本仅映射到单个链接(听起来像您这样做),则可以构建一个关联的查找数组。我自己只是遇到了这种需求。这是我的处理方式。这样,您就不需要每次都遍历所有链接。

function populateOutlines($htmlOutlines)
{
  $marker = "courses";
  $charSlashFwd = "/";
  $outlines = array();
  foreach ($htmlOutlines->find("a") as $element)
  {
    // filter links for ones with certain markers if required
    if (strpos($element->href, $marker) !== false)
    {
      // construct the key the way you need it
      $dir = explode($charSlashFwd, $element->href);
      $code = preg_replace(
        "/[^a-zA-Z0-9 ]/", "", strtoupper(
          $dir[1]." ".$dir[2]));
      // insert the lookup entry
      $outlines[$code] = $element->href;
    }
  }
  return $outlines;
}
// ...stuff...
$htmlOutlines = file_get_html($urlOutlines);
$outlines = populateOutlines($htmlOutlines);
// ...more stuff...
if (array_key_exists($code, $outlines)) {
  $outline = $outlines[$code];
} else {
  $outline = "n/a";
}