如何获取PHP中的所有数组值?

时间:2015-06-25 13:37:32

标签: php arrays

我一直在尝试使用模板创建新页面,其中一些字符串替换为某些数组中的值。页面创建适用于特定的阵列号。但是,我希望从数组中的所有值创建新页面,而不仅仅是一个或两个特定值。

这是到目前为止的代码:

<?php

 $dom= file_get_html($url);
 $array_title = array();
 $array_details = array();
 foreach ($dom->find('div[class=main]') as $results) {
        foreach ($results->find('title') as $title) {
        $array_title[] = $title->alt;
        }

        foreach ($results->find('div[class=details]') as $details) {
        $array_descript[]= $details->innertext;
        }
 }
 {
    $page = str_replace("{title}", $array_title[3], $template);
    $page = str_replace("{descript}", $array_descript[3], $page);


     //create a name for the new page
    $pagename =  $array_title[3].".php"; 

    //put the created content to file
    file_put_contents("article/".$pagename,$page);
 }

?>

回显时的数组:

 Array
 (
  [0] => Guacamole 
  [1] => Buffalo Chicken Dip
  [2] => Jalapeno Popper Spread
  [3] => Seven Layer Taco Dip
  [4] => Brown Sugar Smokies
  [5] => Baked Kale Chips

)

Array
(
 [0] => Guacamole recipe
 [1] => Buffalo Chicken Dip recipe
 [2] => Jalapeno Popper Spread recipe
 [3] => Seven Layer Taco Dip recipe
 [4] => Brown Sugar Smokies recipe
 [5] => Baked Kale Chips recipe
 )

上面的代码创建了一个新页面,其中包含数组中第3行的值。我已尝试将数组编号设为空白[ ],但它返回以下错误:PHP Fatal error: Cannot use [ ] for reading

我可以获得一些洞察力,以获得我期待的所有数组值吗? 提前致谢

1 个答案:

答案 0 :(得分:0)

请按照我建议的更改继续上面的代码:

<?php

 $dom= file_get_html($url);
 $array_title = array();
 $array_details = array();
 foreach ($dom->find('div[class=main]') as $results) {
        foreach ($results->find('title') as $title) {
        $array_title[] = (string)$title->alt;
        }

        foreach ($results->find('div[class=details]') as $details) {
        $array_descript[]= (string)$details->innertext;
        }
 }
 {
    $page = str_replace("{title}", $array_title[3], $template);
    $page = str_replace("{descript}", $array_descript[3], $page);


     //create a name for the new page
    $pagename =  $array_title[3].".php"; 

    //put the created content to file
    file_put_contents("article/".$pagename,$page);
 }

?>