简体   繁体   English

打印数组到文件

[英]Printing out an array to a file

I'm stuck on particular task. 我被困在特定的任务上。 As you can see I'm extracting hrefs and title from webpage and I need to put this information to a file. 如您所见,我正在从网页中提取href和标题,我需要将此信息放入文件中。 But how this array can be printed in order like this: href1 : title1 , href2 : title2 and so on. 但是如何按以下顺序打印此数组:href1:title1,href2:title2等等。

   <?php
   $searched = file_get_contents('http://technologijos.lt');
   $xml = new DOMDocument();
   @$xml->loadHTML($searched);
   foreach($xml->getElementsByTagName('a') as $lnk) 
      {
         $links[] = array(
         'href' => $lnk->getAttribute('href'),
         'title' => $lnk->getAttribute('title')
      );
      }
   echo '<pre>'; print_r($links); echo '</pre>';
   ?>

Why not create the array directly in a way that is usable afterwards? 为什么不以以后可用的方式直接创建数组?

<?php
$searched = file_get_contents('http://technologijos.lt');
$xml = new DOMDocument();
@$xml->loadHTML($searched);

$links = [];
foreach($xml->getElementsByTagName('a') as $lnk) {
    $links[] = sprintf(
        '%s : %s', 
        $lnk->getAttribute('href'), 
        $lnk->getAttribute('title');
    );
}

var_dump(implode(', ', $links);

Obviously the same can be done by using a second loop to iterate over the links array if it is create as shown in your example. 显然,如果您的示例中所示创建了第二个循环,则可以通过第二个循环遍历links数组来完成此操作。

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

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