简体   繁体   English

在PHP上使用DOMDocument进行foreach循环

[英]foreach loop with DOMDocument on PHP

This code doesn't get out any thing, even the 0 . 这段代码没有任何意义,甚至0也没有。

<?php
     $html = '<a href="abc" >Hello world!</a><a href="abcdef" >Hello  </a>';
     $html = '<div>' . $html . '</div>';
     $doc = new DOMDocument;
     $doc->loadHTML($html);
     $links = $doc->getElementsByTagName('a')->item(0);
     foreach ($links as $link){
         echo "0";
         echo $dom->saveHTML($link->getAttribute('href');
     }
     // Outputs: "<h1>Hello world!</h1>"
 ?>

Please try this 请尝试这个

$html = '<a href="abc" >Hello world!</a><a href="abcdef" >Hello  </a>';
$dom = new DOMDocument;
        @$dom->loadHTML($html);

foreach($dom->getElementsByTagName('a') as $link) {
    echo $link->nodeValue;
}

You will have to drop the ->item(0) following your getElementsByTagName call or you will just get the first anchor element in $links (which is why the foreach does not do what you want it to). 您必须在getElementsByTagName调用之后删除->item(0)否则您将只获得$links的第一个锚元素(这就是为什么foreach不会执行您想要的操作的原因)。 The saveHTML call will also have to be removed. saveHTML调用也必须删除。

$html = '<a href="abc" >Hello world!</a><a href="abcdef" >Hello  </a>';
$html = '<div>' . $html . '</div>';
$doc = new DOMDocument;
$doc->loadHTML($html);

// Drop the ->item(0)
$links = $doc->getElementsByTagName('a');

foreach ($links as $link){
    // Remove saveHTML call
    echo $link->getAttribute('href'), PHP_EOL;
}

Output: 输出:

abc
abcdef

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM