无法用getAttribute上的file_put_contents替换echo

时间:2013-10-17 18:46:55

标签: php

我正在尝试运行file_put_contents而不是echo,但我无法解决它。 这是我的代码:

$DOM = new DOMDocument();
$DOM->loadHTML($html);
$a = $DOM->getElementsByTagName('a');
foreach($a as $link){
    echo $link->getAttribute('href').'<br />';

我尝试更新echo $link->getAttribute('href').'<br />';与file_put_contents("$project.txt", $link->getAttribute('href').'<br />');但不是得到这样的东西:

http://domain1.com/url-page-1/
http://domain2.com/url-page-2/
http://domain3.com/url-page-3
(...)

我得到了这个:

http://domain1.com/url-page-1/<br />

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

改为使用PHP_EOL

file_put_contents("$project.txt", $link->getAttribute('href').PHP_EOL);

如果要附加到该文件,请使用FILE_APPEND标志:

$text = $link->getAttribute('href').PHP_EOL;
file_put_contents("$project.txt", $text , FILE_APPEND);

您的foreach循环如下所示:

foreach($a as $link){
    echo $link->getAttribute('href').'<br />';
    $text = $link->getAttribute('href').PHP_EOL;
    file_put_contents("$project.txt", $text , FILE_APPEND);
}