The file below, can be setup using any JPG file from PhotoShop that has XMP data. In the 'pattern', replace 'eat:' with 'dc:' or any namespace returned from the '$string'.
Calling $string (1) using following array setup it produces a print_r array that looks like: (2)
If you uncomment the line ubove (1a), it will print to the browse, copy & paste into the line below (1a). this should produce an array that looks like: (3)
Why the difference print_r readings, when it's the same string?
How do I get it to behave like (3); ... better yet how do I make it end up like the(4)?
<?php
header("Content-Type: text/html; charset=utf-8");
$filename = "2012-04-24_WestCoast_2.jpg";
echo '<img src="'. $filename . '" alt="'. $filename . '" title="' . $filename . '" width="350" /><p />';
$source = file_get_contents($filename);
$xmpdata_start = strpos($source,'<x:xmpmeta');
$xmpdata_end = strpos($source,"</rdf:Description>");
$xmplenght = $xmpdata_end-$xmpdata_start;
$xmpdata = substr($source,$xmpdata_start,$xmplenght+18);
$string = htmlentities($xmpdata); //(1)
//if (is_string($string)) {
// echo "is a string\n"; //TRUE
//} else {
// echo "is not a string\n";
//}
//$string = print_r("'".$string."';");
// (1a)=====================================
//$string = '<x:xmpmeta xmlns: === Truncated for simplicity ===x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.3-c011 66.145661, 2012/02/06-14:56:27 "> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"></rdf:Description>';
$pattern = '/eat:(.*?)="(.*?)"/is';
preg_match_all($pattern, $string, $matches);
$group = array($matches[1], $matches[2]);
// foreach($group as &$match);
echo '<pre>';
// print_r ($match);
print_r ($group);
echo '</pre>';
?>
(2)=====================================
// If i just call the '$string', this is what i get:
Array
(
[0] => Array
(
)
[1] => Array
(
)
)
(3)=====================================
// If I uncomment (1), the '$string' that I pasted inside the file, i get this:
Array
(
[0] => Array
(
[0] => Biography
[1] => Title
[2] => object_description
[3] => Medium
[4] => in_height
[5] => in_width
[6] => in_depth
[7] => Dated
[8] => Photograph
)
[1] => Array
(
[0] => American B1942 Castine, Maine
[1] => Reunion Dinner Party at the Slanted Door
[2] => Nancy Freeman, Tim Patterson The Slanted Door San Francisco Calf.
[3] => photography
[4] => 2736
[5] => 3648
[6] => # 240 dpi
[7] => April 24, 2012
[8] => PrimaryImage
)
)
(4)=====================================
// This is what i'm trying to get too:
Biography: American B1942 Castine, Maine
Title: Reunion Dinner Party at the Slanted Door
object_description: Reunion Dinner Party at the Slanted Door
Nancy Freeman, Tim Patterson The Slanted Door San Francisco Calf.
Medium: photography
in_height: 2736
in_width: 3648
in_depth: # 240 dpi
Dated: April 24, 2012
Photograph: PrimaryImage
I'm not clear on what the issue is with the string being set inside or outside of file. It is unclear what you are trying to explain.
The output of the array(3) is caused by the brackets in the Regular Expression. I don't know the exact reason for this, but to get the results you want(4) you could use a loop to join the two arrays in a new array.
Note: What your doing with $group is making an array of arrays. You are not merging the two arrays into one. To merge the arrays you need to iterate through both arrays and merging each element as new element of new array.
example:
for($i=0; $i<match[0].length; $i++){
$result[i] = $match[0][i]. ": " .$match[1][i];
}
Im rusty on my php, but that is the idea for merging the arrays.
--EDIT--
Now that I understand what you are trying to do I see two possible places where problems may occur. First is: are you 100% sure the image you are using contains any meta data in the fields you want? Im not sure of the exact nature of meta data, but I do know there will be the required data set by the computer(what you filtered out with the start and end points), and the custom data. If blank it might not even be included.
Second possible issue is how you are chunking up the meta data. Maybe try writing to Regular Expressions to strip the start and end from the string. Replace everything in front of a set of characters with "" and do a similar expression for the back.
Also the variable you set for $group is the exact same thing that $match was. You took the two arrays that where contained in the array %match and assigned them to an array called $group. Just a FYI. Use the sudo code I posted earlier to design the loop that will actually combine the two arrays into one.
Good Luck. Maybe when I get php set up on testing computer I will play with the code to see what exactly is happening.
Well it looks like i get to answer my own question of "Why it is a called 'string' invisible to an array?".
The answer is: When it's preceded by a call to 'htmlentities()'.
Now I'm not really sure why it happens but it does happen and the instant I went back and checked all my assumptions ... that 'htmlentities()' would clean up the raw string. Commenting out 'htmlentities()' made everything work.
Is this a bug? I personally don't know, and i don't have the necessary experience using PHP to even hazard a guess. What i do know is it drove me up the wall for a week.
Related
This question already has an answer here:
How to retrieve variable="value" pairs from m3u string
(1 answer)
Closed 3 years ago.
Hope you guys can help me out. I have the following .m3u file
#EXTM3U
#EXTINF:-1 tvg-id="" tvg-name="A&E" tvg-logo="" group-title="ENTRETENIMIENTO",A&E
http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/76.ts
#EXTINF:-1 tvg-id="" tvg-name="ABC Puerto Rico" tvg-logo="" group-title="NACIONALES",ABC Puerto Rico
http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/96.ts
#EXTINF:-1 tvg-id="" tvg-name="Animal Planet" tvg-logo="" group-title="ENTRETENIMIENTO",Animal Planet
http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/185.ts
As you can see, there is the main tag for the file
#EXTM3U and down that start the video information tag (#EXTINF:-1 ...) and down that the video link entry (http:// .....)
Can you explicitly tell me how can i parse this whole file (it's a pretty large one) and save the fields in an array for example like this? videos[ ]
and later i can acces to every video attributes lets say videos[0]['title'] for getting the title for the first video? and so on with the other attributes for example videos[42]['link'] and get the link to the video #42.
I am already using curl to get the file content into a variable like this
<?php
$handler = curl_init("link to m3u file");
$response = curl_exec ($handler);
curl_close($handler);
echo $response;
?>
What i need now is to parse the Curl response and save all the videos information into an array, where i can acces to every attribute of every video.
I know i must use some regexp or something like that. i just dont understand how. can you please help me with some code? thank you so much.
Behold the magik of Regx
$string = <<<CUT
#EXTM3U
#EXTINF:-1 tvg-id="" tvg-name="A&E" tvg-logo="" group-title="ENTRETENIMIENTO",A&E`http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/76.ts
http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/76.ts
#EXTINF:-1 tvg-id="" tvg-name="ABC Puerto Rico" tvg-logo="" group-title="NACIONALES",ABC Puerto Rico
http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/96.ts
CUT;
preg_match_all('/(?P<tag>#EXTINF:-1)|(?:(?P<prop_key>[-a-z]+)=\"(?P<prop_val>[^"]+)")|(?<something>,[^\r\n]+)|(?<url>http[^\s]+)/', $string, $match );
$count = count( $match[0] );
$result = [];
$index = -1;
for( $i =0; $i < $count; $i++ ){
$item = $match[0][$i];
if( !empty($match['tag'][$i])){
//is a tag increment the result index
++$index;
}elseif( !empty($match['prop_key'][$i])){
//is a prop - split item
$result[$index][$match['prop_key'][$i]] = $match['prop_val'][$i];
}elseif( !empty($match['something'][$i])){
//is a prop - split item
$result[$index]['something'] = $item;
}elseif( !empty($match['url'][$i])){
$result[$index]['url'] = $item ;
}
}
print_r( $result );
Returns
array (
0 =>
array (
'tvg-name' => 'A&E',
'group-title' => 'ENTRETENIMIENTO',
'something' => ',A&E`http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/76.ts',
'url' => 'http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/76.ts',
),
1 =>
array (
'tvg-name' => 'ABC Puerto Rico',
'group-title' => 'NACIONALES',
'something' => ',ABC Puerto Rico',
'url' => 'http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/96.ts',
),
)
Seriously though I have no clue what some of this is something for example. Anyway should get you started.
For the regx, it's actually pretty simple when it's broken down. The real trick is in using preg_match_all instead of preg_match.
Here is our regx
/(?P<tag>#EXTINF:-1)|(?:(?P<prop_key>[-a-z]+)=\"(?P<prop_val>[^"]+)")|(?<something>,[^\r\n]+)|(?<url>http[^\s]+)/
First we will break it down to more manageable bits. These are separated by the pipe | for or. Each one can be thought as a separate pattern, match this one or the next one. Now, the order can be important, because they will match left to right so if one matches on the left it stops. So you have to be careful no to have a regx that can match in two places ( if you don't want that ). However, it can be used to your advantage too, as I will show below. This is really what we are dealing with
(?P<tag>#EXTINF:-1)
(?:(?P<prop_key>[-a-z]+)=\"(?P<prop_val>[^"]+)")
(?<something>,[^\r\n]+)
(?<url>http[^\s]+)
Four regular expressions. For all of these (?P<name>...) is a named capture group, it just makes it more readable, easier to find the bits. If you look at the conditions I use to find the matches, for example!empty($match['tag'][$i]), we can use the tag index/key because of a named capture group, otherwise it would be 1. With a number of regx all together, having 1 2 3 can get messy if you consider this is actually nested so it would be $match[1][$i] for tag etc. Anyway, once that is taken out we have
#EXTINF:-1 match this string literally
(?:(?P<prop_key>[-a-z]+)=\"(?P<prop_val>[^"]+)") this is more complicated (?: .. ) is a non-capture group, this is so the key/value winds up with the same index in the match array but not captured togather, Broken down this is ([-a-z]+)=\"([^"]+)\" or match a word followed by = then " than anything but a " ending with ". Basically one side captures the key, the other the value excluding the double quotes
,[^\r\n]+ starts with a comma then anything but a line return
and last http[^\s] a url
Now remember what I said about order being important, this url http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/76.ts would match the last expression, except that it starts with ,A&Ehttp://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/76.ts` which matches the 3rd one so it never gets to number 4
Hope that helps, granted you'll have to have a basic grasp of Regx, this is not really the place for a full tutorial on that, and you can find better examples then I can provide in a few short minutes.
Just for the sake of completeness, here is part of what preg_match_all returns
(
[0] => Array(
[0] => #EXTINF:-1
[1] => tvg-name="A&E"
[2] => group-title="ENTRETENIMIENTO"
[3] => ,A&E`http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/76.ts
[4] => http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/76.ts
[5] => #EXTINF:-1
[6] => tvg-name="ABC Puerto Rico"
[7] => group-title="NACIONALES"
[8] => ,ABC Puerto Rico
[9] => http://nxtv.tk:8080/live/jarenas/iDKZrC56xZ/96.ts
)
[tag] => Array(
[0] => #EXTINF:-1
[1] =>
[2] =>
[3] =>
[4] =>
[5] => #EXTINF:-1
[6] =>
[7] =>
[8] =>
[9] =>
)
[1] => Array(
[0] => #EXTINF:-1
[1] =>
[2] =>
[3] =>
[4] =>
[5] => #EXTINF:-1
[6] =>
[7] =>
[8] =>
[9] =>
)
[prop_key] => Array(
[0] =>
[1] => tvg-name
[2] => group-title
[3] =>
[4] =>
[5] =>
[6] => tvg-name
[7] => group-title
[8] =>
[9] =>
)
[2] => Array( ... duplicate of prop_key .. )
etc.
)
The way to find the item in the above array is if you look at the for loop when it runs the first time index 0, the main part of the match $match[0][$i] contains all the matches, but the tag array only contains the items that match that regx, we can correlate them using the $i index.
if( !empty($match['tag'][$i])){
//is a tag increment the result index
++$index;
}
If $match[tag][$i] is not empty. which if you look at $match[tag][0] when $i = 0 you will see that indeed it is not empty. On the second loop $match[tag][1] is empty but $match[prop_key][1] is not so we know that when $i = 1 item is a prop_key match. That's how that works.
-ps- if you can find a way to remove the duplicated numeric indexes, please share it with me ... lol ... these are the normal matches if I didn't use a named capture group, as I said it can get messy.
I did a simple working m3u8 parser in php.
it's a remote m3u8 file parser to json but it easy to change the output
https://github.com/onigetoc/m3u8-PHP-Parser
I may soon change it or add a CURL parser instead of file_get_contents().
m3u-parser.php?url=https://raw.githubusercontent.com/onigetoc/m3u8-PHP-Parser/master/ressources/demofile.m3u
Once you get the CURL Response then read the file from Remote Location via CURL or fopen function.
For that you have read the files that are into directory from remote location and save all the files into Local server.
You can use the file function "Stat" for the getting all the information and keep into the $files
I have given the idea regarding how to collect all information and then you can create array.
Once the Array is created you can serialize the response for printing.
I noticed that str_getcsv doesn't seem to enclose the first value it receives in double quotation marks, even when the string data is passed this way.
In the example below, the first value in the 3rd row is "Small Box, But Smaller", but after running it through str_getcsv it becomes Small Box, But Smaller (without double quotation marks). Like this:
// multi-line csv string
$csvString = <<<'CSV'
"Title","Description",Quantity
"Small Box","For storing magic beans.",2
"Small Box, But Smaller","Not sure why we need this.",0
CSV;
// split string into rows (don't use explode in case multi-line values exist)
$csvRows = str_getcsv($csvString, "\n"); // parse rows
echo '<pre>';
print_r($csvRows);
echo '</pre>';
Outputs:
Array
(
[0] => Title,"Description",Quantity
[1] => Small Box,"For storing magic beans.",2
[2] => Small Box, But Smaller,"Not sure why we need this.",0
)
The problem this causes is that now if each row is parsed using str_getcsv, a comma in the first value makes it split into two rows. If it keeps running this:
foreach($csvRows as &$csvRow) {
$csvRow = str_getcsv($csvRow); // parse each row into values and save over original array value
}
unset($csvRow); // clean up
// output
echo '<pre>';
print_r($csvRows);
echo '</pre>';
Outputs:
Array
(
[0] => Array
(
[0] => Title
[1] => Description
[2] => Quantity
)
[1] => Array
(
[0] => Small Box
[1] => For storing magic beans.
[2] => 2
)
[2] => Array
(
[0] => Small Box
[1] => But Smaller
[2] => Not sure why we need this.
[3] => 0
)
)
The problem is in the last array value, which is an array of 4 keys instead of 3. It's split on the comma of the value "Small Box, But Smaller".
On the other hand, parsing just one row string works:
$csvRowData = '"Small Box, But Smaller","Not sure why we need this.",0';
$csvValues = str_getcsv($csvRowData);
echo '<pre>';
print_r($csvValues);
echo '</pre>';
Outputs:
Array
(
[0] => Small Box, But Smaller
[1] => Not sure why we need this.
[2] => 0
)
Why is this happening and how do I solve the problem with multi-line CSV data? Is there a best practice for working with multi-line CSV data when it is a string and is not read directly from a file? Also, I need to handle multi-line values, such as "foo \n bar" so I can't just use explode() instead of the first str_getcsv().
After much headache I think I understand the problem now. According to the PHP folks, "str_getcsv() is designed to parse a single CSV record into fields" (see https://bugs.php.net/bug.php?id=55763). I discovered that using str_getcsv() for multiple rows causes these not-so-well documented problems:
Double quotation marks are not maintained (as I demontrate above).
Line breaks in values cause it to think a new row has begun. This can have many unintended consequences.
I solved the issue by creating a temporary file and writing the CSV content to it. Then I read the file using fgetcsv(), which did not result in the 2 issues I described above. Example code:
// multi-line csv string
$csvString = <<<'CSV'
"Title","Description",Quantity
"Small Box","For storing magic beans.",2
"Small Box, But Smaller","This value
contains
multiple
lines.",0
CSV;
// ^ notice the multiple lines in the last row's value
// create a temporary file
$tempFile = tmpfile();
// write the CSV to the file
fwrite($tempFile, $csvString);
// go to first character
fseek($tempFile, 0);
// track CSV rows
$csvRows = array();
// read the CSV temp file line by line
while (($csvColumns = fgetcsv($tempFile)) !== false) {
$csvRows[] = $csvColumns; // push columns to array (really it would be more memory-efficient to process the data here and not append to an array)
}
// Close and delete the temp file
fclose($tempFile);
// output
echo '<pre>';
print_r($csvRows);
echo '</pre>';
Results in:
Array
(
[0] => Array
(
[0] => Title
[1] => Description
[2] => Quantity
)
[1] => Array
(
[0] => Small Box
[1] => For storing magic beans.
[2] => 2
)
[2] => Array
(
[0] => Small Box, But Smaller
[1] => This value
contains
multiple
lines.
[2] => 0
)
)
I'll also add that I found some options on GitHub, and 2 major projects for PHP 5.4+ and PHP 5.5+. However, I am still using PHP 5.3 and only saw options with limited activity. Furthermore, some of those processed CSV strings by writing to files and reading them out also.
I should also note that the documentation for PHP has some comments about str_getcsv() not being RFC-compliant: http://php.net/manual/en/function.str-getcsv.php. The same seems to be true for fgetcsv() yet the latter did meet my needs, at least in this case.
I don't know why you PHP_EOL is not working correctly as it does on my server however I did encounter this problem before.
The approach I took goes as follows.
Firstly I like to make sure all my fields are surrounded by double quotes regardless of the value in the field so to use your example text (with some slight modifications):
// multi-line csv string
$csvString = <<<CSV
"Title","Description","Quantity"
"Small Box","For storing magic beans.","2"
"Small Box, But Smaller","Not sure why we need this.","0"
"a","\n","b","c"
CSV;
$csvString .= '"a","' . "\n" . '","' . PHP_EOL . '","c"';
Secondly I target solo PHP_EOL that may be lingering in values so I can replace any "PHP_EOL" strings with "\r\n"
// Clear any solo end of line characters that are within values
$csvString = str_replace('","' . PHP_EOL . '"', '",""',$csvString);
$csvString = str_replace('"' . PHP_EOL . '","', '"","',$csvString);
$csvString = str_replace('"' . PHP_EOL . '"', '"'. "\r\n" . '"',$csvString);
and then finally this allows me to use the php explode function and display output:
$csvArr = explode("\r\n",$csvString);
foreach($csvArr as &$csvRow) {
$csvRow = str_getcsv($csvRow); // parse each row into values and save over original array value
}
unset($csvRow); // clean up
// output
echo '<pre>';
print_r($csvArr);
echo '</pre>';
Which outputs:
Array
(
[0] => Array
(
[0] => Title
[1] => Description
[2] => Quantity
)
[1] => Array
(
[0] => Small Box
[1] => For storing magic beans.
[2] => 2
)
[2] => Array
(
[0] => Small Box, But Smaller
[1] => Not sure why we need this.
[2] => 0
)
[3] => Array
(
[0] => a
[1] =>
[2] => b
[3] => c
)
[4] => Array
(
[0] => a
[1] =>
[2] =>
[3] => c
)
)
As you can see from the output the new line characters are not targeted, just the PHP_EOL.
I've looked and can't find a solution to this feature we would like to write. I'm fairly new to PHP so any help, advice and code examples are always greatly appreciated.
Let me explain what we want to do...
We have a block of HTML inside a string - the content could be up to 2000 words with styling such as <p>, <ul>, <h2> included in this HTML content string.
We also have an array of images related to this content inside a separate string.
We need to add the images from the array string into the HTML content at equal spaces without breaking the HTML code. So a simple character count won't work as it could break the HTML tags.
We need to equally space the images. So, for example; if we had 2000 words inside the HTML content string and 10 images in the array, we need to place an image every 200 words.
Any help or coding samples provided in order to achieve this is greatly appreciated - thank you for your help in advance.
You can use
$numword = str_word_count($str, 0);
for getting the number of row
or
$array = str_word_count($str,1);
for getting in $array an array with all the word (one for index) and then iterating on this array for rebuild text you need adding every number of time (word) the code for your image
This Sample is form php Manual
<?php
$str = "Hello fri3nd, you're
looking good today!";
print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àáãç3'));
echo str_word_count($str);
?>
this is related result
Array
(
[0] => Hello
[1] => fri
[2] => nd
[3] => you're
[4] => looking
[5] => good
[6] => today
)
Array
(
[0] => Hello
[6] => fri
[10] => nd
[14] => you're
[29] => looking
[46] => good
[51] => today
)
Array
(
[0] => Hello
[1] => fri3nd
[2] => you're
[3] => looking
[4] => good
[5] => today
)
7
You can find it in this doc
for the insert you can try this way
$num = 200; // number of word after which inert the image
$text = $array[0]; // initialize the text with the first word in array
for ($cnt =1; $cnt< count( $array); $cnt++){
$text .= $array[$cnt]; // adding the word to the text
if (($cnt % $num) == 0) { // if array index multiple fo 200 insert the image
$text .= "<img src='your_img_path' >";
}
}
I have tried for the last two days now searching on google and in all the forums, but can't seem to find any answer that remotely helps me with this problem .
I have a stock feed .csv file which I need to change the values of the shoe sizes to work with Woocommerce. The shoe sizes are different on each row.
The sizes in the csv are listed like this: 4-10, 5-12, 3-9 etc. one set of numbers per row 4-10. I have inputed the file into an array in my php script.
So for each shoe I have an array like this:
Array
(
[0] => 4578
[1] => kors
[2] => red
[3] => wedge
[4] => 4-10
)
I need to take the last value e.g. 4-10 and change them to something like this: 4|5|6|7|8|9|10.
So basically I need to take the first number in the element and increment it by 1 and separate it with the pipe character " | "until it reaches the value of the last number. Then I need it to replace the 4-10 in the element with the 4|5|6|7|8|9|10.
This should work for you:
(Here I first get the last element of the array and explode() it with - as delimiter. After this I simply create an array with range() where I use the $start and $end variable. At the end I simply save the element back by implode()'ing it.)
<?php
$arr = [4578, "kors", "red", "wedge", "4-10"];
list($start, $end) = explode("-", $arr[count($arr)-1]);
$arr[count($arr)-1] = implode("|", range($start, $end));
print_r($arr);
?>
output:
Array ( [0] => 4578 [1] => kors [2] => red [3] => wedge [4] => 4|5|6|7|8|9|10 )
I am upgrading the way my website runs, I have already integrated mant php scripts in pages, but I am trying to develop fully php based site, eg, instead of loading urls:
url/events/event-1
url/events/event-2
^^^ 2 seperate pages
I am trying to load
url/event?url=event-1
this is so I can update 1 page but load different content depending on the
$_GET['url']
parameter.....
what I have so far...
I load url/event?url=dance
it will automatically search a directory for the filename 'dance.txt'
if the file does not exist, it forwards to main events page (url/events)
if the files does exist, it creates a one line string about the event....
the file content is listed like this:
Dance::::18-02-2012::::http://{external link}::::Event Information
the script I have developed to import this data and display it, works fine, but I need a page that will load all events each in a separate div.......
producing this page is simple enough if I can figure out how to arrange the event array data into a multidimensional array for all events...
for individual events, the script simply defines variables as:
$name, $date, $link, $writeup
I have attached sample code of how I do this...
$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];
this works perfectly for individual pages, however, I need to have an array like this:
$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 )
);
this is how I presume the array would be formed, but I need the script to count how many files there are in the /data/ folder, and then (I'm presuming) have a foreach loop so that for each array (event) I can echo:
<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>'.$name.' Online</p>
</div>
</div><!-- post -->
</div><!-- content2 -->
I know it may seem a complicated way of going around things, but this way my site will be 100% editable via data in txt files, as right now I have to clone existing page, then re-write all content in it for new event!
foreach($files as $key => $value) {
$array[] = array(explode('::::',(file_get_contents('data/'.$files[$key].'.txt'))));
}
print_r($array);
gives me:
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.
)
)
)
aha nearly done.
ps I would like foreach to list by dates stated in each txt file, it currently lists alphabetically from filenames...
Borrowed a bit of Jribeiro's code to actually read the files into the two-dimensional array.
$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);
Then, to loop through the $items array:
foreach($items as $item){
$name = $item["Name"];
echo "Name is $name<br>";
// etc
}
Although, I'm required to inform you to look into using MySQL to do this as it is much easier, safer, and more powerful than using a flat text file.
If you want the number of files in dir you can try this:
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;
}
I'm actually not quite sure if i understood your problem correctly.
But at the end you want to store a nested array $events in a flat file and read it back to an array?
I would suggest using serialize to do this, then it's quite simple:
$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"));