【问题标题】:get text from a <li>从 <li> 获取文本
【发布时间】:2012-05-03 18:29:09
【问题描述】:

我在&lt;div&gt; 中有几个&lt;li&gt; 标签,如下所示:

<li> <a href="link1"> one <li>
<li> <a href="link2"> two <li>
<li> <a href="link3"> three <li>

如何使用 HTML DOM 解析器获取文本 two,然后将其放入数组中以供以后使用?

【问题讨论】:

  • 您想在 PHP(服务器端)或 javascript/JQuery(客户端)中这样做?
  • 您问题中的 html 有问题。您有 9 个打开的标签,没有一个关闭。很难按原样解析。

标签: php html parsing domparser


【解决方案1】:

您需要确保 a 标记已关闭,然后您可以这样做:

<?php 
$html = '<li> <a href="link1"> one </a> <li>
<li> <a href="link2"> two </a> <li>
<li> <a href="link3"> three </a> <li>
';

// Create a new DOM Document
$xml = new DOMDocument();

// Load the html contents into the DOM
$xml->loadHTML($html);

// Empty array to hold all links to return
$result = array();

//Loop through each <li> tag in the dom
foreach($xml->getElementsByTagName('li') as $li) {
    //Loop through each <a> tag within the li, then extract the node value
    foreach($li->getElementsByTagName('a') as $links){
        $result[] = $links->nodeValue;
    }
}
//Return the links
print_r($result);
/*
Array
(
    [0] =>  one 
    [1] =>  two 
    [2] =>  three 
)

*/
?>

所有内容都在domDocument的手册中

【讨论】:

  • 谢谢我只是对第二个 FOREACH 部分感到困惑,这很清楚
  • 如果您通过 id 获得第一个元素,您可以直接在 a 上进行 foreach。只是一个提示。
  • 谢谢,但由于某种原因,getelementbyid 对我不起作用
  • 就像@hakre 说的你可以直接去搜索a 元素,简单地使用foreach($li-&gt;getElementsByTagName('a') as $links)getElementById 不能工作,因为没有指定id。
【解决方案2】:

考虑使用Simple HTML Dom Parser 来实现这一点。示例代码:

// include the simple html dom parser
include 'simple_html_dom.php'; 

// load the html with one of the sutiable methods available with it
$html = str_get_html('<li><a href="link1">one</a></li><li><a href="link2">two</a></li>');

// create a blank array to store the results
$items = array();

// loop through "li" elements and store the magic plaintext attribute value inside $items array
foreach( $html->find('li') as $li ) $items[] = $li->plaintext;

// this should output: Array ( [0] => one [1] => two ) 
print_r( $items );

【讨论】:

    猜你喜欢
    • 2023-02-16
    • 2018-01-19
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 2021-07-27
    • 1970-01-01
    相关资源
    最近更新 更多