PHP, Create dynamic list from files in a directory - php

I have a directory of files who's main purpose is to store php variables for inclusion into other files in the site. Each file contains the same set of variables, but with different values.
for example:
event1.php
<?php
$eventActive = 'true';
$eventName = My First Event;
$eventDate = 01/15;
?>
event2.php
<?php
$eventActive = 'true';
$eventName = My Second Event;
$eventDate = 02/15;
?>
In addition to calling these variables in other pages, I want to create a page that contains a dynamic list, based on the variables stored in each file within the directory.
Something like (basic concept):
for each file in directory ('/events') {
if $eventActive = 'true'{
<p><? echo $eventName ?></p>
}
}
What is the best way to do this?

Create an Event class or an array of each event. Then populate it from the directory.
$index = 0;
foreach (array_filter(glob($dir.'/*'), 'is_file') as $file) {
#include $file; // Parses the file, so the variables within are set.
$events[$index]['active'] = $eventActive;
$events[$index]['name'] = $eventName;
$events[$index]['date'] = $evetnDate;
$index++;
// OR
// $events[] = new Event($eventName, $eventDate, $eventActive);
}
// Now the $events array contains all your events.
// List out the active ones
foreach ($events as $event) {
echo ($event['active'] === 'true') ? $event['name'] : '';
// OR
// echo $event->isActive() ? $event->getName() : '';
}

Ok, so I spend some time with it and was able to reslove the issue with a cleaner solution, but utilizing an external json file to store the values
<?php
$json = file_get_contents('events.json');
$jsonArray = json_decode($json, true); // decode the JSON into an associative array
foreach ($jsonArray as $value) {
if (($value['active'] === 't') && ($value['fromDate'] >= $currentDate)) {
echo '<p>'.$value['title'].' '.$value['fromDate'].' - '.$value['toDate'].'</p>';
}
}
echo $currentDate;
?>

Related

How do I loop different sections inside a contentful landing page with php

Using the php SDK, I would like to get all the content for a landing page, this will include sections with different content types / components with different fields per entry.
eg.
Section 1 - hero
Section 2 - article
Section 3 - image
Q. How do I loop through and get the linked section content.
If an entry contains a link to an asset or another
entry, the SDK will automatically load it.
I am struggling to understand the documentation. How exactly do I break into these values?
<?php
$query = new \Contentful\Delivery\Query();
$query->setContentType('page_landing')
->where("fields.urlHandle[match]", $slug);
$products = $client->getEntries($query);
foreach ($products as $product) {
echo $product['name'];
// Example of what I am trying to achieve
if($product['sections']['id']=='hero'){
$title= $product['sections']['hero']['title'];
}
if($product['sections']['id']=='article'){
$text = $product['sections']['article']['text'];
}
}
?>
I would love to know if there is a better way, the documentation does not have many examples. Below is where I ended up but feel there must be a simpler way.
<?php
require_once 'vendor/autoload.php';
require_once 'vendor/credentials.php';
// if we need to use rich text
$renderer = new \Contentful\RichText\Renderer();
// Get the section entry id's
foreach ($products as $product) {
$dataJson = json_encode($product);
$revertJson[] = json_decode($dataJson, true);
foreach ($revertJson as $Json) {
foreach ($Json['fields']['sections'] as $entries) {
$entryID[] = $entries['sys']['id'];
}
}
}
// Loop out the sections
foreach ($entryID as $entry) {
// Get individual linked entries
$entry = $client->getEntry($entry);
$type = $entry->getSystemProperties()->getcontentType();
$json = json_encode($type);
$comp = json_decode($json, true);
if ($comp['sys']['id'] == 'Hero') {
// field
echo $entry['urlHandle'];
// rich text
echo $renderer->render($entry['text']);
// asset
$asset = $client->getAsset($entry['imageId']);
echo $asset->getFile()->getUrl();
} elseif ($comp['sys']['id'] == 'Landmark') {
echo $entry['title'];
}
}

Passing Array values into Function

I am trying to pass an array value into a function, but can't seem to get it to work. Here is what I am trying to do
I have a folder on my server called /Rpt
The /Rpt folder has a bunch of different folders inside of it (30 of them) - these folders contain a bunch of different files in them
I want to check most of the folders in /Rpt, and get the name and date of the latest file (based on last modified or created date) ... i want to store the results into an array, that has (folder path, file name of last file, file date of last file)
This query gets the folders that need to be checked
$sql = "my SQL here";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);
This is a function that checks the specified folder, and displays the info i need (folder path, file name, file date)
function GetFileNameDate($location, $file_name, $file_date) {
$files = scandir($location);
$path = $location;
foreach ($files as $file) {
if (strpos($file, " ") !== false) {
$filename = $file;
$last_updated = date ("F d Y H:i:s", filemtime($path.'\\'.$file));
$results = array($filename=>$last_updated);
$file_name = key($results);
$file_date = reset($results);
return array($location, $file_name, $file_date);
}
}
}
When i call the function - and enter a specific path link in this example, it works OK and i shows the values i want to see
$FileNameDate = GetFileNameDate('E:\Rpt\FolderA');
echo $FileNameDate[0];
echo $FileNameDate[1];
echo $FileNameDate[2];
echo "<br/><br/>";
This is where I am having problems
I am trying to pass an array (list of folders from my SQL query) into the function, so i can output the (folder path, name of latest file, date of latest file) for each of the folders from SQL query
When i echo $locations (it lists all the folders which i am trying to pass to the function)
foreach ($arrValues as $row){
$locations = array($row['Folder']);
$FileNameDate = GetFileNameDate($locations);
echo $FileNameDate[0];
echo $FileNameDate[1];
echo $FileNameDate[2];
}
As per suggestion from #lovelace I also tried the following, but again just a blank page.
foreach ($arrValues as $row){
$locations = array($row['Folder']);
foreach ($locations as $FolderPath) {
$FileNameDate = GetFileNameDate($FolderPath);
echo $FileNameDate[0];
echo $FileNameDate[1];
echo $FileNameDate[2];
}
}
SOLUTION
see comment below to how above was fixed ... however I ended up implementing what i wanted a different way, sharing it in case anyone else needs similar functionality
function GetFileNameDate($location) {
$files = scandir($location);
$path = $location;
foreach ($files as $file) {
$iterator = new DirectoryIterator($path);
$mtime = 0;
$file = "";
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
if ($fileinfo->getMTime() > $mtime) {
$file = $fileinfo->getFilename();
$mtime = $fileinfo->getMTime();
}
}
}
return array($path, $file, $mtime);
}
}
foreach ($arrValues as $row){
$locations = array(rtrim($row['Folder']));
foreach ($locations as $FolderPath) {
$FileNameDate = GetFileNameDate($FolderPath);
echo $FileNameDate[0]; #folder
echo $FileNameDate[1]; #file
echo $FileNameDate[2]; #date
}
}

php - Compare name files in directory with sql row

I am trying to create a script that compare the names of the files in a directory with a row in my database in order to get all the files that are not present in the database list.
The script I have so far prints out the files in the directory however when I try to compare the values with my sql I have a lot of results repeated.
How can I compare the name of the files in order to get all the name files that are not listed in my database?
Directory:
a.mp4
0.mp4
b.mp4
34.mp4
c.mp4
Database rows:
> Date---------------Name---------------video_path
> 01-01-01----------|jonh--------------|a.mp4
> 02-01-01----------|andrea------------|b.mp4
> 03-01-01----------|faith-------------|c.mp4
result should be:
0.mp4
34.mp4
SCRIPT:
$directory = '/var/www/html/EXAMPLE/resources/';
$files1 = scandir($directory, 1);
if ( $files1 !== false )
{
//$filecount = count( $files );
foreach ($files1 as $i => $value) {
$sqlfindTmp = "SELECT * FROM `videos`";
if ($resultTmp = mysqli_query($conn,$sqlfindTmp)) {
while ($row=mysqli_fetch_row($resultTmp)) {
if ($row[3] == $value) {
}else{
echo $value . "<br/>";
}
}
}
}
}
else
{
echo 0;
}
The way you have structured your code right now is that it makes an SQL query for every file and on each of those queries it retrieves the whole database, which might not be a problem right now but when your dataset grows will slow things down.
I would suggest restructuring your code so you first query the database for all filenames, save this to an array and then loop through the files, checking if they are in the database.
// Query database
$sqlFind = 'SELECT `video_path` FROM `videos`';
$result = mysqli_query($conn, $sqlFind);
$db = []; // create empty array
while ($row = mysqli_fetch_row($result))
array_push($db, $row[0]);
// Check files
$files1 = scandir($directory, 1);
if ( $files1 !== false ) {
foreach ($files1 as $i => $value) {
if (in_array($value, $db)) {
// File exists in both
} else {
// File doesn't exist in database
}
}
} else {
echo 0;
}
I agree with Kalkran, get the 'video_path' values into an array and do this once. scandir returns all the filenames into an array as well. So you can use a simple array_diff to get an array of files in the directory that aren't in 'video_path'.
So I would try :
$sqlFind = 'SELECT `video_path` FROM `videos`';
$result = mysqli_query($conn, $sqlFind);
$db = []; // create empty array
while ($row = mysqli_fetch_row($result))
array_push($db, $row[0]);
// Check files
$files1 = scandir($directory, 1);
$filesOfInterest = $files1 ? array_diff($files1,$db) : null;

JSON search event names and list URL values

I'm loading event listing as an JSON-File from an URL:
$file = file_get_contents('http://ecample.com/listing.php?');
$data = json_decode($file);
?>
The direct output looks like this (more values and mor lines):
[{"id":"1","name":"NAME_1","booking_url":"https://ecample.com/Event_ID65654","category_id":"195"},
{"id":"2","name":"NAME_2","booking_url":"https://ecample.com/Event_ID65654","category_id":"195"},
"id":"1","name":"NAME_1","booking_url":"https://ecample.com/Event_ID65654","category_id":"195"}]
I need to search for all entrys with the value "name":"NAME_1" and print out the value of "booking_url".
I tried different things like array_seach() etc. but did not work out.
Any help is appreciated!
try this
<?php
$file = file_get_contents('http://ecample.com/listing.php?');
$data = json_decode($file, true);
foreach ($data as $r)
{
if ($r['name'] == 'NAME_1')
{
echo $r['booking_url'];
}
}
?>
The other option is to access your data in object context, thus:
<?php
$file = file_get_contents('http://ecample.com/listing.php?');
$data = json_decode($file);
foreach ($data as $r)
{
if ($r->name == 'NAME_1')
{
echo $r->booking_url;
}
}
?>
Either one should work just as well.

building an associative array

This is going to be my first time building an associative array. And if anyone can help me I would be grateful.
Basically, I want to loop through a directory of XML files. I want to find out if a certain editor was the editor of this file, and if the query is true, I would like to grab two pieces of information and achieve the result of an associate array with those two pieces of information for every case where the editor's name is found.
So here's what I have got so far:
function getTitleandID($editorName) {
$listofTitlesandIDs = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
if ($editorName == $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()"))
{
$title = $xmldoc->xpath("//tei:teiHeader/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id[1]");
$listofTitlesandIDs[] = //I don't know what to do here
}
else
{
$listofTitlesandIDs = null;
}
}
return $listofTitlesandIDs
}
This is about where I get stuck. I'd like to be able have $listofTitlesandIDs as an associative array where I could call up the values for two different keys, e.g. $listofTitlesandIDs['title'] and $listofTitlesandIDs[$id]
So that's about it. I'm grateful for any help you have time to provide.
Well I'm sure this is a little clumsy (the result of an amateur) but it has given me the result I want.
function getTitlesandIDs($EditorName) //gets titles and IDs for given author
{
$list = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
$title = $xmldoc->xpath("//tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id");
$editorName = $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()")
if ($editorName[0] == "$EditorName")
{
$result = array("title"=>$title[0], "id"=>$id[0]);
$list[] = $result;
}
}
return $list;
}
With this I can call the function $list = getTitlesandIDs('John Doe') and then access both the title and id in the associative array for each instance. Like so:
foreach ($list as $instance)
{
echo $instance['title'];
echo $instance['id'];
}
Maybe that will help somebody some day -- let me know if you have any advice on making this more elegant.
$listofTitlesandIDs[$id] = $title;
You should loop over the array then using the foreach loop.

Categories