2012-02-18 2 views
-2
나는 내 웹 사이트가 실행되는 방식을 업그레이드하고

, 난 이미 페이지에있는 녀 mant의 PHP 스크립트를 통합 한,하지만 난 예를 들어 완전히 PHP 기반 사이트를 개발하기 위해 노력하고 있습니다 :multidimentional 배열 PHP는 플랫 파일

url/events/event-1 
url/events/event-2 

^^^이 별도의 페이지

내가이 그렇게이다 내가 한 페이지를 업데이트 할 수 있지만

에 따라 다른 내용을로드 할 수 있습니다

url/event?url=event-1 

로드하려고

$_GET['url'] 

매개 변수 .....

내가 가지고 지금까지 ..... 자동으로 디렉토리를 검색합니다

내가 URL/이벤트를로드? URL = 춤 파일이 존재하지 않는 경우 파일 이름 'dance.txt'

, 그것은 주요 행사 페이지로 전달 (URL/이벤트) t 경우

그는

파일 내용은 다음과 같이 표시됩니다 ....는 이벤트에 대한 한 줄의 문자열을 생성, 존재하는 파일 :

Dance::::18-02-2012::::http://{external link}::::Event Information 

내가이 데이터를 가져 와서 표시하기 위해 개발 한 스크립트, 잘 작동하지만 별도의 div에있는 모든 이벤트를로드 할 페이지가 필요합니다 .......

이 페이지를 생성하는 방법은 간단합니다. 이벤트 배열 데이터를 다 중형으로 배열하는 방법을 알면 간단합니다. 모든 이벤트에 대한 배열 .....

$dir = '/server/htdocs/data/';  // path to dir with all event txt files in 
$files = scandir($dir); 

$fruit = array_shift($files); 

$fruit2 = array_shift($files); // array shifts remove values of '.' and '..' 

$line = implode(" ",$files); // back into string for str_replace 

// echo $line; 

$oldword = ".txt"; 

$newword = ""; 

$newline = str_replace($oldword, $newword, $line); 

// echo $newline; 


$files = explode(" ", $newline); // array of filenames 

if (in_array($url, $files)) { 
    $contents = file_get_contents('data/'.$url.'.txt'); 
} else { header('Location: http://{url}/events'); } 

$info = explode('::::', $contents); 

// print_r($info); 

$name = $info[0]; 

$date = $info[1]; 

$link = $info[2]; 

$writeup = $info[3]; 

이 있지만, 내가 필요, 개별 페이지에 대해 완벽하게 작동합니다 .....

$name, $date, $link, $writeup 

나는이 작업을 수행하는 방법의 예제 코드를 첨부 : 연간 이벤트는, 스크립트는 단순히 변수를 정의 이 같은 배열을 가지고 :

$events = array (array (Name => event-1, 
          Date => date-1, 
          Link => link-1, 
          Writeup => event-info), 

        array (Name => event-2, 
          Date => date-2, 
          Link => link-2, 
          Writeup => event-info), 

        array (Name => event-3, 
          Date => date-3, 
          Link => link-3, 
          Writeup => event-info) 
         ); 

내가 배열이 형성 될 것이라고 추정하는 방법이 있습니다,하지만 난 다음 (메신저 추정) 거기에/데이터/폴더에, 얼마나 많은 파일을 계산하는 스크립트를 필요 foreach를 가지고있다 영업 이익은 각 배열 (이벤트)을 위해 내가 에코 할 수 있도록 :

<div id="content2"> 
        <div class="post"> 
<center><h2><u>'.$name.' ('.$date.')</u></h2></center> 
         <p class="postmeta"></p> 
         <div class="entry"> 

<CENTER><img src="events/posters/'.$name.'.jpg" height="400" width="500"></center> 

<p><p> 

<p>'.$writeup.'</p> 

<p><a href="'.$link.'" " target="_blank">'.$name.' Online</a></p> 



</div> 
        </div><!-- post --> 
       </div><!-- content2 --> 

을 때, 나는 그것이 일의 주위에가는 복잡한 방법을 보일 수 있습니다 알고 있지만,이 방법은 내 사이트가 TXT 파일의 데이터를 통해 100 % 편집 할 것 지금은 기존 페이지를 복제 한 다음 새 이벤트를 위해 모든 컨텐츠를 다시 작성해야합니다 !!!!

아무도 도와 줄 수 있으면 감사합니다.

EDIT .....그것은 현재 파일 이름에서 알파벳 순으로 나열

Array 
(
    [0] => Array 
     (
      [0] => Array 
       (
        [0] => 5th-Element 
        [1] => 11-02-2012 
        [2] => http://www.5thelementrocks.co.uk/ 
        [3] => 5th Element are a 5 piece classic rock covers band gigging in venues across the North-West and Wales. Our set lists include tracks by all the greats, including AC/DC, The Cult, Muse, Bon Jovi, Nirvana, Whitesnake, The Darkness, Ozzy Osbourne, and many more. </p><p>We are a high quality, high energy, experienced classic rock band who work hard and play hard to get the audience going and to make sure each gig is a pro performance. Whether were playing for a crowd of one or one thousand, we always give 110% to keep you shakin all night long! 
       ) 

     ) 

    [1] => Array 
     (
      [0] => Array 
       (
        [0] => BBGM 
        [1] => 25-02-2012 
        [2] => http://nwb.co/bbgm 
        [3] => BBGM are four 40-50 something musicians (twin guitars, vocals, bass & drums) who were all in various bands years ago, playing and touring all over the North of England & Europe in the 1980s including working and recording with the now legendary producer Gil Norton.</p><p>In 2007 they got together to form BBGM to gig again. Now an established band on the Northwest circuit we are currently gigging throughout the North West and North Wales playing classic rock covers from the 70's 80's and 90's throwing in one or two original tracks penned over the years. 
       ) 

     ) 

    [2] => Array 
     (
      [0] => Array 
       (
        [0] => Plastic-Sarcasm 
        [1] => 18-02-2012 
        [2] => http://www.facebook.com/pages/PLASTIC-SARCASM/284242054943613?sk=info 
        [3] => Four lads who are still burning. Having the desire to kick ass every now and then through the music they create.</p><p>Originally formed in 1978 by current member Phil Narayan together with Paul Wynne, Phil Tonge and Baz Yates, the Band played in the Punk Rock scene era in and around Bolton. Having not played guitar (but played drums for a couple of years from 1986 1989) on stage for over thirty years, Phil Narayan couldn't resist a late urge to enjoy the feeling of playing live on stage once again. Regularly practising with PLUM (joined the band as singer in 1980) who, now plays Bass guitar and sings, the pair set about making the dream happen once again. They recruited Gordon Connolly for an extra guitar who has been playing throughout his life with various bands, in September 2010. Finally, drummer Gag Martin joined up in reply to an advert at the local rehearsal studios in May 2011.</p><p>"Having had 9 practice/Jammin sessions the band played their first gig in Little Lever on 17th December 2011 where all the old Punk songs were revived. The gig was a screaming success and it is the intention to do more gigs in 2012 when the band will gradually introduce their own numbers more and more as gigs go by." 
       ) 

     ) 

    [3] => Array 
     (
      [0] => Array 
       (
        [0] => Whipcord 
        [1] => 17-02-2012 
        [2] => http://www.facebook.com/whipcord 
        [3] => Doobie Brothers in Bad Brains t-shirts, whistling The Hollies on the way to a Pentagram gig, reading The Wire...it's rock n roll!!</p><p>Whipcord are a stentorian rock n roll power trio from Salford, Manchester UK. Within the noise is a classicist rock feel, drowning in a tar pool of punk rock fury. Being described as the bastard child of Motorhead and Foo Fighters. and that of polished anarchy, not unlike The Whos live shows. 
       ) 

     ) 

) 

거의 내가 각 txt 파일에 명시된 날짜에 의해 나열하는 foreach 문을 싶습니다

PS 도움들에 대한 감사를 수행 AHA :

foreach($files as $key => $value) { 

$array[] = array(explode('::::',(file_get_contents('data/'.$files[$key].'.txt')))); 

} 

print_r($array); 

나를 준다 .... thanks

+0

한 질문에 너무 많은 시간을 소비합니다. – Tim

+1

DB보다 훨씬 느리다는 것을 알고 계십니까?! 가능한 인코딩 문제 등 ... 그냥 – jribeiro

+0

하하 그래, 그 동안 얘기했다 –

답변

1

Jribeiro의 코드를 실제로 2 차원 배열로 읽어 들이기 위해 약간의 차용을했다.

$items = array(); 
if ($handle = opendir($dir)) { 
    while (false !== ($file = readdir($handle))) { 
     $fp = fopen("$file","r"); 

     while($line = fgets($fp)){ 
      $parts = explode("::::",$line); 
      $newArr["Name"] = $parts[0]; 
      $newArr["Date"] = $parts[1]; 
      $newArr["Link"] = $parts[2]; 
      $newArr["Writeup"] = $parts[3]; 
      $items[] = $newArr; // add newArr to items 
     } 
     fclose($fp); 
    } 
    closedir($handle); 
} 

print_r($items); 

다음, $items 배열을 루프 : 비록

foreach($items as $item){ 
    $name = $item["Name"]; 
    echo "Name is $name<br>"; 
    // etc 
} 

, 나는 훨씬 쉽고 안전으로이 작업을 수행하기 위해 MySQL을 사용 들여다 알려하는 데 필요한, 그리고 더있어 텍스트 파일을 사용하는 것보다 강력합니다. 당신은 당신이 시도 할 수 있습니다 디렉토리에있는 파일의 수를 원하는 경우

+0

이것은 유망 해 보입니다.하지만 동적 페이지를로드 할 때 파일 이름을 검색해야하므로 각 이벤트마다 다른 .txt 파일이 있습니다. 파일 이름이 존재하지 않으면 다른 페이지로 전달됩니다. –

+0

답변을 주셔서 감사합니다. 그리고 어쩌면 거기에 여러 파일에 대해 이것을 쓰는 다른 방법이 있습니다. –

+0

오, 오케이, 오해했습니다. – Tim

1

는 :

function fileCounter($dir){ 
    $counter = 0; 
    if ($handle = opendir($dir)) { 
     //echo "Directory handle: $handle\n"; 
     //echo "Files:\n"; 
     /* This is the correct way to loop over the directory. */ 
     while (false !== ($file = readdir($handle))) { 
      //echo "<BR>".$counter." - $file"; 
      $counter++; 
     } 
     closedir($handle); 
    } 
    $counter -= 1; // in order to exclude '.' and '..', as well as start the counter on 1 
    return $counter; 
} 
+0

오늘 제가 작성한 코드는 오늘 자신의 배열에있는 모든 파일 이름을 나열하고 '.' 및 '..'그리고 난 이미 func $ count = count ($ files) –

+0

그래서 내가 얼마나 많은 이벤트의 변수가 필요하면 기술적으로 배열 값의 양을 계산할 수 ..... ..... 그러나 나는 각 텍스트 파일 데이터를 배열에 추가하여 각각 하나씩 반복하고 각 데이터를 출력 할 수 있습니다. –

+0

오, 오해 미안합니다 ... 위의 대답이 올바른 방법 인 것 같습니다. 이 문제가 해결되었는지 나중에 확인하겠습니다 :) – jribeiro

0

을 나는 실제로 내가 정확하게 문제를 이해하면 아주 확실하지 않다. 그러나 결국에는 플랫 파일에 중첩 배열 $events을 저장하고 배열로 다시 읽으려고합니까? 내가이 일을 serialize을 사용하는 것이 좋습니다 것, 그것은 매우 간단합니다

$events = array (array (Name => event-1, 
          Date => date-1, 
          Link => link-1, 
          Writeup => event-info), 

        array (Name => event-2, 
          Date => date-2, 
          Link => link-2, 
          Writeup => event-info), 

        array (Name => event-3, 
          Date => date-3, 
          Link => link-3, 
          Writeup => event-info) 
         ); 
file_put_contents("/foo/bar",serialize($events)); // BAM, it's in the file :) 
//reading it back is equally simple 
$events2 = unserialize(file_get_contents("/foo/bar")); 
+0

죄송합니다. 각 파일의 각 이벤트에 대한 세부 정보가 포함 된 폴더에 몇 개의 플랫 파일이 있습니다 ..... 가장 빠른 날짜순으로 정렬 된 각 txt 파일 세부 정보를 읽고 출력해야 각 텍스트 파일 세부 정보를 출력해야합니다. –