![](/img/trans.png)
[英]PHP: Simple HTML DOM Parser - how to get the element which has certain tag name?
[英]PHP: Simple HTML DOM Parser - how to get the element which has certain content?
在PHP中,我使用的是Simple HTML DOM Parser類。
我有一個包含多個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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.