【问题标题】:How to parse a list using simple html dom [closed]如何使用简单的 html dom 解析列表 [关闭]
【发布时间】:2014-12-25 08:17:12
【问题描述】:

我有一个 html 代码,我在解析这个 html 中的数据时遇到了问题,特别是从下面给出的部分:

<li id=xyz>
  John Johnson
<sup>1<sup>
","
</li>

我想从这个列表中提取“John Johnson”而不是别的。不知道该怎么做。谢谢。

【问题讨论】:

    标签: php html parsing html-lists simple-html-dom


    【解决方案1】:

    find('text') 是您所追求的。它返回在源代码中找到的所有文本块。

    根据您的示例,这是一个工作代码:

    // Test data
    $input = <<<_DATA_
        <li id=xyz>
          John Johnson
        <sup>1<sup>
        ","
        </li>
    _DATA_;
    
    //Create a DOM object
    $html = new simple_html_dom();
    // Load HTML from a string
    $html->load($input);
    
    // >> Long answer
    echo "Long answer:<br/>";
    
    // Search all text nodes inside the target node
    $search = $html->find('li#xyz text');
    
    // Loop through each node and print it
    foreach( $search as $i => $txt ) {
        // No need to specify "->plaintext" since the content is already in plain text here
        echo "$i => " . $txt->plaintext . "<br/>";
    }
    
    // >> Short answer
    echo "<hr>";
    echo "Short answer:<br/>";
    
    // Specifying the index (0th here) returns the Nth element from the array containing all search results
    echo $html->find('li#xyz text', 0)->plaintext;
    
    // Clear DOM object
    $html->clear();
    unset($html);
    

    输出:

    Long answer:
    0 => John Johnson 
    1 => 1
    2 => "," 
    3 => 
    -------------------
    Short answer:
    John Johnson
    

    更多详情请查看Manual

    【讨论】:

    • 非常有帮助!谢谢!
    【解决方案2】:

    用点赞将您需要的内容包围起来。 与

    <li id='xyz'>
      <span>John Johnson</span>
      <sup>1<sup>
        ","
    </li>
    

    然后在您的 javascript 上,假设您使用的是 jquery。

    var contentToGrab =  $('#xyz span').text();
    // just verify you get the data correctly
    console.log(contentToGrab);
    

    【讨论】:

      【解决方案3】:

      使用简单的 javascript,您可以为 span 提供一个类或 Id 并从 javascript 中获取它

      <span id="grabIt">John Johnson</span>
      

      还有你的 javascript:

      Var john=document.getElementById("grabIt").innerText;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-03
        • 2013-04-22
        • 1970-01-01
        • 2014-03-18
        • 1970-01-01
        相关资源
        最近更新 更多