Sign up to create your own snipts, or login.

Public snipts » toledot's snipts » PHP reads from text file and write into YML file

posted on Jan 28, 2010 at 2:05 p.m. EST in 
  • <?
    $arr=file("province.txt");// the txt file to be read
    // read the data from province.txt and write into 02_district.yml
    $myFile = "02_district.yml"; 
    //open a new file with name $myFile, if permission is dennied, throws message
    $fh = fopen($myFile, 'w') or die("can't open file");
    // write the head in YML file without backspace
    $head= "District:\n";
    fwrite($fh, $head);
    $i = 0;
    $k = 0;
    $tmp = "province";
    foreach($arr as $str)
    {
      $k++;
      // split $str, if digits were found
      list($province,$district)=preg_split("/[\d]+/", $str);;
      /*echo "<ul>";
      echo "<li>".$province;
      echo "<li>".$district;
      echo "</ul>";
      echo "<hr>";*/
    
      $district_id = "  District_".$k.":\n";// \n change line
      $district_name = "    name:  ".$district."";
      if($tmp != $province){//if province is changed, increase the id of province
    	  $i++;  
    	  $tmp = $province;
      }
      $province_id = "    province_id:  Province_".$i."\n";
      fwrite($fh, $district_id);//write the value in file
      fwrite($fh, $district_name);
      fwrite($fh, $province_id);
    }
    fclose($fh);
    
    ?> 
    
    // this is text file to be read by PHP script
    Nuristan	3001	Nuristan
    Nuristan	3002	Kamdesh
    Nuristan	3003	Waygal
    Nuristan	3004	Mandol
    Nuristan	3005	Bargi Matal
    Nuristan	3006	Wama
    Nuristan	3007	Du Ab
    Nuristan	3008	Nurgaram
    Sari Pul	3101	Sari Pul
    Sari Pul	3102	Sangcharak
    Sari Pul	3103	Kohistanat
    Sari Pul	3104	Balkhab
    Sari Pul	3105	Sozma Qala
    Sari Pul	3106	Sayyad
    Sari Pul	3107	Gosfandi
    

    copy | embed

0 Comments

Sign up, or login to leave a comment.