Formatting PHP explode array into HTML - php

We have a client who wants to output cinema listings on their website. This particular cinema has provided us with a link to retrieve the information from. This link is simply outputted in plain text, with the elements seperated by ~|~
I am using explode and strpos to divide the listings into divs however it still isn't good enough for what I am wanting to achieve. I just can't get my head around what I can do to format this correctly. This is my code:
<?php
$theArray = explode("~|~", file_get_contents("THE URL"));
echo "<ul id=\"cinemaListings\">";
foreach($theArray as $item){
$findcinemaid = '~77';
$findcinemaname = 'Cinema Name';
$findx = 'X';
$findu = 'U';
$findgen = 'Gen';
$findlink = '.ie';
if(strpos($item, $findcinemaname) !== false){
echo "<div class='cinemaName'>" . $item . "</div>";
}elseif(strpos($item, $findgen) !== false){
echo "<div class='cinemaGen'>" . $item . "</div>";
}elseif(strpos($item, $findcinemaid) !== false){
echo "<li>";
}elseif($item == $findx){
echo "<div class='cinemaX'>" . $item . "</div>";
}elseif(strlen($item) == 8){
echo "<div class='cinemaCode'>" . $item . "</div>";
}elseif(strlen($item) == 3){
echo "<div class='cinemaListId'>" . $item . "</div>";
}elseif(strlen($item) == 2){
echo "<div class='cinemaListId'>" . $item . "</div>";
}elseif(strlen($item) == 1){
echo "<div class='cinemaListId'>" . $item . "</div>";
}elseif(DateTime::createFromFormat('H:i', $item) !== FALSE){;
echo "<div class='cinemaTime'>" . $item . "</div>";
}elseif(strpos($item, $findlink) !== false){
echo "<div class='cinemaLink'>" . $item . "</div>";
}elseif(DateTime::createFromFormat('d/m/Y', $item) !== FALSE){;
echo "<div class='cinemaDate'>" . $item . "</div>";
}else {
echo "<div>" . $item . "</div>";
}
}
echo "</ul>";
?>
This script however is outputting (with divs and classes of course, just don't want to add them all):
<li>The Smurfs 2 2D 30/08/2013 11:10</li>
<li>The Smurfs 2 2D 30/08/2013 13:20</li>
<li>The Smurfs 2 2D 31/08/2013 11:10</li>
<li>The Smurfs 2 2D 31/08/2013 13:20</li>
<li>Elysium 04/09/2013 15:45</li>
<li>Elysium 04/09/2013 21:00</li>
<li>Elysium 05/09/2013 15:45</li>
Is there any possible way to format it as follows:
<li>
The Smurfs 2 2D
30/08/2013 (today's date)
11:10 13:20
</li>
<li>
Elysium
04/09/2013 (today's date)
15:45 21:00
</li>
So just one film name, todays date and the times for that day (with classes ofcourse). Then onto the next film... etc.
I'm stuck and would appreciate any help! Thanks in advance.

Are you talking about the source layout or the front end html layout? If it's the source layout, have you tried replacing this:
echo "<div class='cinemaName'>" . $item . "</div>";
With this(?):
echo "<div class='cinemaName'>" . preg_replace( ' ', "\r\n", $item ) . "</div>";
Since it looks like there are 3 spaces between each segment of the $item, you can replace them with return shorthand \r\n (or just \n for some systems).
If it's the front end layout, just use the same method, but instead of \r\n, change it to <br/>.

Related

How can I generate a set of HTML list items from \n newline separated string using php?

How can I generate a set of HTML list items from \n newline separated string using php?
I'm using the Google Sheet PHP API with a foreach loop
// authentication not shown
$range = 'Sheet3!AD2:Z';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
foreach($values as $val) {
$valuespan = "<span class=\"record\">".implode($val)."</span>";
echo $valuespan;
}
to get the HTML output of all rows in the Google Sheet wrapped in span markup like this:
(the \n newlines are shown for illustration)
<span class="record">Customer 1 \n
Exercise Physiologist \n
PT, DPT, COMT \n
Class Name \n
South Physical Therapy \n
City 1 \n
AR \n
</span>
<span class="record">Customer 2 \n
Exercise Physiologist \n
PT \n
Class Name \n
Central Therapy \n
City 2 \n
AL \n
</span>
...on and on to the last row of the Sheet.
I need to be able to use the \n delimiter to add markup, as I can't use a comma, due to commas being in the data; and I can't add any other delimiters to the Sheet.
So what I need is this specific markup; I need each Customer in <h1> tags and the other items in <li></li> tags, like this:
<span class="record">
<h1>Customer 1</h1>
<ul>
<li>Exercise Physiologist</li>
<li>PT, DPT, COMT</li>
<li>Class Name</li>
<li>South Physical Therapy</li>
<li>City 1</li>
<li>AR</li>
</ul>
</span>
I also need to account for empty items, i.e. if the "Class Name" doesn't exits, skip outputting the <li></li> for that item.
I've looked at this question Generate a set of HTML list items from a comma separated list? PHP but I get the error
explode(): Argument #2 ($string) must be of type string, array given.
How can I explode/implode to output the needed html?
Or is there another php function more useful?
Edit 12/13/21
I found I needed to be able to use if constructs for some fields, and that didn't work with concatenating the string, so this is what I'm using. It may be ugly in a programmatical sense; if so, add comments.
foreach($values as $val) {
$valuearray =explode("\n", implode($val)); // explode string into array
$name = $valuearray[0];
$focus = $valuearray[1];
$certification = $valuearray[2];
$course = $valuearray[3];
$business = $valuearray[4];
$url = $valuearray[5];
$address = $valuearray[6];
$city = $valuearray[7];
$state = $valuearray[8];
echo '<h1 class="name">' . $name . '</h1>';
echo '<ul>';
if($focus ?? true) {echo '<li class="focus">Focus: ' . $focus . '</li>'; }
if($certification ?? true) {echo '<li class="certification">Certification: ' . $certification . '</li>'; }
if($course ?? true) {echo '<li class="course">Course: ' . $course . '</li>'; }
if($url ?? true) {
echo '<li class="business">Business: <a class="business-link" target="_blank" rel="noopener noreferrer" href="https://' . $url . ' ">' . $business . '</a></li>';
} elseif ($business ?? true) {
echo '<li class="business">Business: ' . $business . '</li>';
}
if($address ?? true) {
echo '<li class="address">Location: ' . $address . ', ' . $city . ', ' . $state . '</li>';
} else {
echo '<li class="address">Location: ' . $city . ', ' . $state . '</li>';
}
echo '</ul>';
}
Because your cell values use \n as a delimiter, first use the explode function to explode the cell value from a string to an array. Then, take the first item of this array to add as the header.
The first parameter of the implode function can be used for a separator. You can pass all but the first entry of your array into this function using the array_slice function. If you want your array items to display as an unordered list, you can use "</li><li>" as your separator. To skip empty list items you can use str_replace to replace all instances of "<li></li>".
foreach($values as $val) {
$valuearray = explode("\n", implode($val)); // explode string into array
$valuespan = "<span class=\"record\">";
$valuespan = $valuespan . "<h1>" . $valuearray[0] . "</h1>"; // add heading
$valuespan = $valuespan . "<ul><li>" . implode("</li><li>", array_slice($valuearray, 1)) . "</li></ul></span>"; // add remaining array as list items
$valuespan = str_replace("<li></li>", "", $valuespan); // remove empty list items
echo $valuespan;
}

Grouping/Ordering Items in PHP Object Array

I have a sitemap that I'm trying to group by URL and stack them based on URL. Here is the sitemap https://www.sitecentre.com.au/sitemap
Basically, I need this to be dynamic. I can make this easily by doing a case, or if statements, like I've done on the Blog section, but I need it dynamic. It needs to look like this:
<li>Web Design
<ul>
<li>Nested in Web Design</li>
<li>Nested in Web Design</li>
</ul>
</li>
All based on the URL. the URL is /design then the nested would be design/nested
Then the next group would be like branding and nested on branding so it's all organised and laid out perfectly, then alphabetically ordered based on something else.
Here is our current PHP:
<?php
$pages = json_decode(file_get_contents('data/pages.json'));
foreach ($pages as $data){
foreach ($data as $key => $values){
if ($values->status === '1' && $values->visible === '1' && $values->slug !== 'home'){
if ($values->slug !== 'blog'){
echo '<li>' . $values->heading . ' - Last Updated: ' . date('d/m/Y', strtotime($values->date_modified)) . '</li>';
} else {
// Get the latest blogs
$blogs = json_decode(file_get_contents('data/blogs.json'));
echo '<li>' . $values->heading . ' - Last Updated: ' . date('d/m/Y', strtotime($values->date_modified)) . '';
echo '<ul>';
foreach ($blogs as $data){
foreach ($data as $key => $values){
if ($values->status === '1' && $values->visible === '1'){
echo '<li>' . $values->heading . ' - Last Updated: ' . date('d/m/Y', strtotime($values->date_modified)) . '</li>';
}
}
}
echo '</li></ul>';
}
}
}
}
?>
It clearly needs a bit of work in order to make this work, but I cannot for the life of me work out where to start.

How to get value from next iteration of foreach loop

I'm trying to print out entries from a SQL database. Some of the entries are images, and I want to parse those and put them in appropriate HTML markup.
Database Example
id | datatype | typetext
78 | paragraph | "hello"
79 | image | "image.jpg"
80 | paragraph | "goodbye"
The column datatype signifies what type of data is being stored in a given row, and I want to catch when the value of datatype is "image" - then jump to the following typetext column and prepare the appropriate markup for this image.
For instance, some psuedo-code of what I'm trying to do:
if(column is datatype){
if(datatype == 'image'){
echo '<p>' . data inside accompanying typetext column . '</p>';
}
}
Here's my current code:
//the array of the blog entry
foreach($entry as $key => $entryUnit){
//the array of the entry unit
foreach($entryUnit as $column => $cell){
if($column == 'datatype'){
if($key == 'image'){
echo '<br/>';
echo '<p style="color: pink;">' $cell . $entryUnit[$column + 1] . '</p>';
echo '<br/>';
}
}
else if($column == 'typetext'){
echo '<br/>';
echo $cell;
echo '<br/>';
}
}
}
In the first if statement, I try jumping to the next column with echo '<p style="color: pink;">' $cell . $entryUnit[$column + 1] . '</p>';, but this doesn't work.
I've also tried utilizing the next() function, like:
echo '<p>' . next($cell) . '</p>';`
..but this also doesn't work as I thought it would.
You don't need that nested foreach loops, you can everything in just one simple foreach loop.
foreach($entry as $entryUnit){
if($entryUnit['datatype'] == "image"){
echo '<br/>';
echo '<p style="color: pink;">' . $entryUnit['typetext'] . '</p>';
echo '<br/>';
}elseif($entryUnit['datatype'] == "paragraph"){
echo '<br/>';
echo $entryUnit['typetext'];
echo '<br/>';
}
}
Somethink like this should work:
//the array of the blog entry
foreach($entry as $key => $entryUnit){
$i=0;
//the array of the entry unit
foreach($entryUnit as $column => $cell){
if($column == 'datatype'){
if($key == 'image'){
$i++;
echo '<br/>';
echo '<p style="color: pink;">' $cell . $entryUnit[$i] . '</p>';
echo '<br/>';
}
}
else if($column == 'typetext'){
echo '<br/>';
echo $cell;
echo '<br/>';
}
}
}

How to call varying urls in Magento

What I have in my Mage site is:
echo "<div class='block-content'><ul>";
foreach($listeditems as $optionId => $value) {
echo "<li class='item'>" . $value . "</li>";
}
echo "</ul></div>";
But I want it to echo the matching URL instead of a list of search result items.

Help me combine these conditions for determining if this list item begins with a new letter

Maybe I'm having a bad day, but I can't seem to combine these 2 conditions into 1. They obviously should be, because they output the exact same data. The following code creates a list with A-Z to act as anchor links, and is then meant to traverse an array in the format 'word'=>'definition'. I wanted the PHP to output a h3 element with the current letter everytime it detected a new letter.
Here is what I have
$letters = range('A', 'Z');
echo '<em>Jump to:</em><ul class="letters">';
// anchors
foreach ($letters as $letter) {
echo '<li>' . $letter . '</li>';
}
echo '</ul>';
// start listing them!
$currentLetter = 0;
echo '<dl id="botany-words">';
foreach($content as $botanyWord=>$definition) {
if ($botanyWord == key(array_slice($content, 0, 1))) { // must be first, aka 'A'
echo '<h3 id="botany-words-' . $letters[$currentLetter] . '">' . $letters[$currentLetter] . '</h3>';
}
if (substr($botanyWord, 0, 1) != $letters[$currentLetter]) { // if the first character of this botany word is different to the last
echo '<h3 id="botany-words-' . $letters[$currentLetter] . '">' . $letters[$currentLetter] . '</h3>';
$currentLetter++;
}
?>
<dt><?php echo $botanyWord; ?></dt>
<dd><?php // echo $definition; ?></dd>
<?
}
echo '</dl>';
Everytime I tried to do
if ($botanyWord == key(array_slice($content, 0, 1)) || substr($botanyWord, 0, 1) != $letters[$currentLetter])
it didn't work right, and error'd because it overflowed the 26th index (obviously being 26 chars in the alphabet).
Thank you for your assistance!
$currentLetter = '';
foreach($content as $botanyWord=>$definition) {
if ( $currentLetter !== $botanyWord[0] ) {
$currentLetter = $botanyWord[0];
// next letter ...if your array is in lex. order
...
}
...
}

Categories