【问题标题】:how to get innerhtml by classname or id using php如何使用php通过类名或id获取innerhtml
【发布时间】:2014-04-15 08:24:54
【问题描述】:

您好,我正在从外部 url 加载内容。像这样的。

$html=get_data($external_url);

其中 get_data() 是一个使用 curl 获取内容的函数。

现在,我想通过使用它们的类或 id 从不同的 html 元素(如 h1、div、p、span)获取内部 html。

例如 如果来自外部 url($html) 的内容是这样的。

<html>
<title></title>
<body>
    <h1 class="title">I am title</h1>
    <div id="content">
        i am the content.
    </div>
</body>

现在我想获取带有 class="title" 的 html 标记的内部 html。同样,我想获取带有 id="content"

的标签的内部 html

如何使用 php 做到这一点?我对DOM、XML一无所知。请帮忙。

【问题讨论】:

    标签: php xml parsing dom


    【解决方案1】:

    这很容易。试试

    $dom_doc = new DomDocument();
    $dom_doc->loadHTML($returned_external_html);
    $element = $dom_doc->getElementsByTagName('table'); // you can search for any tags like <img>, <p> and etc. This will return a DOMNodeList
    $element = $dom_doc->getElementById('specific_id'); // If you know the id of element you are seeking for try this. This will return a DOMElement
    //If I want to getINNERHTML for the table element, the code should be:
    $innerHTML= ''; 
    $children = $element->childNodes; 
    foreach ($children as $child) { 
        $innerHTML .= $child->ownerDocument->saveXML( $child ); 
    }
    echo $innerHTML; //contain the inner html of the element
    

    查看这些链接以获得更多帮助
    DOMDocument GetElementsByTagName
    DOMDocument GetElementById

    【讨论】:

    • 谢谢。但我如何获得innerhtml?我按照你说的试过了。但我收到错误,因为 getElementByID('content'), gelElementByClassName('title');
    • 很容易,您可以使用$dom_doc-&gt;saveXML($element);,它将DOM元素的内部内容作为字符串加上节点本身返回。我更新了我的解决方案,希望对您有所帮助
    【解决方案2】:

    这是一个函数DOMDocument::saveHTML()。在当前的 php 版本中,这可以获取您想要保存为 html 的节点。要保存节点的内部 html,您必须保存每个子节点。

    function getHtml($nodes) {
      $result = '';
      foreach ($nodes as $node) {
        $result .= $node->ownerDocument->saveHtml($node);
      }
      return $result;
    }
    

    要获取节点,您可以使用 Xpath。 id很简单。

    获取所有元素节点:

    //*

    具有 id 属性“内容”

    //*[@id="content"]

    仅使用第一个找到的节点,以防有人多次添加相同的 id。

    //*[@id="content"][1]

    获取子节点 - node() 包括元素、文本和其他几个节点

    //*[@id="content"][1]/node()

    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $xpath = new DOMXpath($dom);
    
    echo getHtml($xpath->evaluate('//*[@id="content"][1]/node()'));
    

    class 属性稍微复杂一些。类属性是令牌列表,它们可以包含多个类名。这是匹配它们的技巧。 Xpath 函数 normalize-space() 将所有空白组转换为单个空格分隔符。在前面和末尾添加一个空格,你会得到一个类似" one two three " 的字符串。现在您可以检查" one " 是否是该字符串的一部分。在 Xpath 中:

    规范化类属性:

    normalize-space(@class)

    在开头和结尾添加空格:

    concat(" ", normalize-space(@class), " ")

    检查它是否包含子字符串

    contains(concat(" ", normalize-space(@class), " "), " title ")

    用它来限制节点

    //*[contains(concat(" ", normalize-space(@class), " "), " title ")][1]/node()

    放在一起:

    $html = <<<'HTML'
    <html>
    <title></title>
    <body>
        <h1 class="title">I am title</h1>
        <div id="content">
            i am the <b>content</b>.
        </div>
    </body>
    HTML;
    
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $xpath = new DOMXpath($dom);
    
    function getHtml($nodes) {
      $result = '';
      foreach ($nodes as $node) {
        $result .= $node->ownerDocument->saveHtml($node);
      }
      return $result;
    }
    
    // first node with the id
    var_dump(
      getHtml(
        $xpath->evaluate('//*[@id="content"][1]/node()')
      )
    );
    
    // first node with the class
    var_dump(
      getHtml(
        $xpath->evaluate(
          '//*[contains(concat(" ", normalize-space(@class), " "), " title ")][1]/node()'
        )
      )
    );
    
    // alternative - handling multiple nodes with the same class in a loop
    $nodes = $xpath->evaluate(
      '//*[contains(concat(" ", normalize-space(@class), " "), " title ")]'
    );
    foreach ($nodes as $node) {
      var_dump(getHtml($xpath->evaluate('node()', $node)));
    }
    

    输出:https://eval.in/118248

    string(40) "
            i am the <b>content</b>.
        "
    string(10) "I am title"
    string(10) "I am title"
    

    【讨论】:

    • 非常感谢。作为一个初学者能够做到这一切,我应该从哪里开始学习以及我应该学习什么。我不了解 dom、xml、xpath。不介意的话可以给个基本的介绍吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2012-05-15
    • 2013-11-04
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 2011-07-28
    相关资源
    最近更新 更多