Retrieving info from a file - php

This code retrieves information from another site:
<?php
$location = $ident;
get_taf($location);
function get_taf($location) {
$fileName = "ftp://tgftp.nws.noaa.gov/data/forecasts/taf/stations/$location.TXT";
$taf = '';
$fileData = #file($fileName);
if ($fileData != false) {
list($i, $date) = each($fileData);
$utc = strtotime(trim($date));
$time = date("D, jS M Y Hi",$utc);
while (list($i, $line) = each($fileData)) {
$taf .= ' ' . trim($line);
}
$taf = trim(str_replace(' ', ' ', $taf));
}
if(!empty($taf)){
echo "Issued: $time Z
<br><br>
$taf";
} else {
echo 'TAF not available';
}
}
?>
What its suppose to look like:
TAF KLBX 160541Z 1606/1706 15009KT P6SM FEW009 BKN013 OVC030
FM160900 15005KT P6SM SCT010 BKN035
FM161600 16010KT P6SM VCSH SCT012 BKN030
FM161900 18012KT P6SM SCT025 BKN040
FM170000 16005KT P6SM SCT012 BKN022
What it ends up looking like:
TAF KLBX 160541Z 1606/1706 15009KT P6SM FEW009 BKN013 OVC030 FM160900 15005KT P6SM SCT010 BKN035 FM161600 16010KT P6SM VCSH SCT012 BKN030 FM161900 18012KT P6SM SCT025 BKN040 FM170000 16005KT P6SM SCT012 BKN022
How do I maintain the spacing with the rows???
It is putting all the info on 1 line and it looks like a paragraoh instead a list.
Thanks

Your output contains newline bytes, but in webpages those line breaks are usually treated as regular spacing characters and not as an actual line break (the br tag is used for hard breaks instead). PHP has a function to convert line breaks to br tags called nl2br, so you could do this:
$taf = nl2br(trim(str_replace(' ', ' ', $taf)), false);
Since you're trimming the line endings of every line you'll also have to modify something to either preserve them (by using trim with two parameters or by using just ltrim) or re-add them manually like this:
$taf .= ' ' . trim($line) . "\n";
You could also append the <br> tags directly, that would save you the conversion. Another possibility would be to just preserve/add the line endings and wrap the output in a <pre> section, this will eliminate the need of break-tags.

Modify the following line
$taf .= ' ' . trim($line);
Using the PHP End of Line constant, like so:
$taf .= ' ' . trim($line).PHP_EOL;

Related

Lines not delimited by CRLF sequence near line # 1

I'm having an issue getting the line folding to work the way it's specified. I'm obviously misunderstanding something about the documentation, so I was hoping I could get some help. The validator at https://icalendar.org/validator.html is saying
Lines not delimited by CRLF sequence near line # 1
Reference: RFC 5545 3.1. Content Lines
This is my function to generate the .ics files for download:
public function getCalendarFile($event) {
header("Content-Type: text/Calendar; charset=utf-8");
header("Content-Disposition: attachment; filename="ExampleFile.ics");
$icsFile = "BEGIN:VCALENDAR\r\n";
$icsFile .= "VERSION:2.0\r\n";
$icsFile .= "PRODID:Example Event" . $event->name . "\r\n";
$icsFile .= "METHOD:PUBLISH\r\n";
$icsFile .= "BEGIN:VEVENT\r\n";
$icsFile .= "UID:". $event->name . gmdate("Ymd\THis\Z", strtotime(Carbon::now())) . "\r\n";
$icsFile .= "DTSTAMP:" . gmdate("Ymd\THis\Z", strtotime(Carbon::now())) . "\r\n";
$icsFile .= "DTSTART:" . gmdate("Ymd\THis\Z", strtotime($event->begin)) . "\r\n";
$icsFile .= "DTEND:" . gmdate("Ymd\THis\Z", strtotime($event->end)) . "\r\n";
$icsFile .= "LOCATION:" . strip_tags($event->location) . "\r\n";
$icsFile .= "SUMMARY:" . $event->name . "\r\n";
$icsFile .= "DESCRIPTION:" . $this->foldCalendarDescription(strip_tags($event->description)) . "\r\n";
$icsFile .= "END:VEVENT\r\n";
$icsFile .= "END:VCALENDAR\r\n";
echo $icsFile;
}
public function foldCalendarDescription($description) {
return wordwrap($description, 75, "\r\n\t", TRUE);
}
I'm not sure if it has something to do with strip_tags possibly? The event description is stored as a wysiwyg html input. But the issue says with line # 1 and line # 1 looks fine to me.
Here's a wrapper for ICAL strings that works for me:
function format_ical_string( $s ) {
$r = wordwrap(
preg_replace(
array( '/,/', '/;/', '/[\r\n]/' ),
array( '\,', '\;', '\n' ),
$s
), 73, "\n", TRUE
);
// Indent all lines but first:
$r = preg_replace( '/\n/', "\n ", $r );
return $r;
}
As I wrote in the comment beneath kmoser's answer, people seem to be really hard pressed to get exactly 75 bytes on a line and create very convoluted code to do that. But why not just sometimes less than 75 bytes? A simple wordwrap will give you that because it just looks for whitespace to break and is not multi-byte aware. You'll possibly have a few more linebreaks in the iCal object code than strictly neccessary, but does that matter? This is why I upvoted kmoser's answer. It's a nice and simple solution.
I've tried to create an even simpler and faster version of kmoser's answer:
function format_ical_string( $str ) {
$str = str_replace(
[ "\r\n", '\\', ',', ';', "\n" ], // replacement order is important
[ "\n", '\\\\', '\,', '\;', '\n' ], $str );
return wordwrap( $str, 73, "\n ", false );
}
The replacements (just a str_replace, because nothing fancy is needed here) are:
replace CRLF's with just LF's
replace literal backslashes with escaped backslashes
escape comma's
escape semicolons
replace newlines with a literal \n (per rfc5545)
Then wordwrap with a LF + space (per rfc5545).
After this, strictly you should replace all LF's with CRLF's (rfc5545 line ending). I tend to format the entire iCal object with just LF's, and only at the very end replace all LF's with CRLF's to make the result compliant. This saves me the hassle of repeatedly inserting these Windows line endings (who uses those these days?) during the composition of my iCal objects.
It is unclear from rfc5545 if the property name itself is counted in the 75 bytes line limit, as in https://www.rfc-editor.org/rfc/rfc5545#section-3.1:
Lines of text SHOULD NOT be longer than 75 octets, excluding the line break.
But just to be sure, I feed the property name to the function, as in:
$line = format_ical_string( 'SUMMARY:Really long text here' );
IMPORTANT: my function above will fail on single words (!) that are longer than 75 bytes. I'm not sure how common that is. If you have an 18-character word completely made of 4-byte characters, you'd be at the limit. This seems very unlikely to me.

Adding paragraph tags around each line in html textarea

I'm trying to make text input in a textarea as easy as possible for the user, without them needing to know any code or have to deal with wysiwyg formatting. It's just text.
But since the text, when shown on the page, will be shown in html, it would be great for there to be 'p' tags around each line.
Right now I've tried this:
$content = mysqli_real_escape_string($connection,$_POST['content']);
$paragraphs = explode("\n", $content);
for ($i = 0; $i < count ($paragraphs); $i++)
{
$paragraphs[$i] = '<p>' . $paragraphs[$i] . '</p>';
}
$content = implode('', $paragraphs);
But this is putting the <p></p> tags around EVERYTHING - one at the beginning of the post, and one at the end, ignoring all returns.
Can anyone see what I'm doing wrong?
When you call mysqli_real_escape_string(), this encodes certain things - from the manual
escapestr
The string to be escaped.
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
So any \n's will be escaped.
You could change it round to do the replacement first...
$paragraphs = explode("\n", $_POST['content']);
for ($i = 0; $i < count ($paragraphs); $i++)
{
$paragraphs[$i] = '<p>' . $paragraphs[$i] . '</p>';
}
$content = implode('', $paragraphs);
BUT you should also be using prepared statements, so you shouldn't need to call mysqli_real_escape_string() at all.

Select the first 90 characters from the content

I am modifying a piece of code, the essence is to pick the first 90 characters from the body of a post. I have managed to get the text including some punctuation characters.
My problem is that I do not know how to get the 90 characters NOT to ignore newline. I want it to terminate once it encounters a line break. As it is now, it doesn't respect it and so ends up adding content from another line/paragraph.
This is the code I am using -
$title_data = substr($postdata,0,90);
$title_data = preg_replace("/[^\w#&,\":; ]/",'', strip_tags($title_data));
$data['post_title'] = "F. Y. I - " . $title_data . " ...";
The right first step you do the preg_replace(), then you put that value to substr() param.
$title_data = preg_replace("/[^\w#&,\":; ]/",'', strip_tags($postdata));
$data = substr($title_data,0,90);
$data['post_title'] = "F. Y. I - " . $data . " ...";
Here's my to cents... It also makes sure words aren't truncated.
// Break the string after the first paragraph (if any)
$parts = explode('</p>', $postdata);
// Remove all HTML from the first element (which contain the full text if no paragraph exists)
$excerpt = strip_tags($parts[0]);
$ending = '...';
if (strlen($excerpt) > 90) {
// Check where the last space is, so we don't truncate any words.
$excerpt = substr($excerpt, 0, 90 - strlen($ending));
$excerpt = substr($excerpt, 0, strrpos($excerpt, ' '));
}
// Return the new string
$data['post_title'] = "F. Y. I - " . $excerpt . $ending;
A bit more complicated, but might help to get the result you're after:
// Use `wpautop` to work WP's paragraph-adding magic.
$rawText = wpautop($postdata);
// Remove all the opening `<p>` tags...
$preSplitContent = str_replace('<p>', '', $rawText);
// ...and then break into an array using the closing `</p>` tags.
// (hacky, but this gives you an array where each
// item is a paragraph/line from your content)
$splitContent = explode('</p>', $preSplitContent);
// Then run your preg_replace
// (because `$splitContent[0]` is only the first
// line of your text, you won't include any content
// from the other lines)
$firstLine = preg_replace("/[^\w#&,\":; ]/",'', strip_tags($splitContent[0]));
// Then trim the result down to the first 90 characters
$finalText = substr($firstLine,0,90);
$data['post_title'] = "F. Y. I - " . $finalText . " ...";

How do I split a Wordpress title at the – in PHP?

I am working on my Wordpress blog and its required to get the title of a post and split it at the "-". Thing is, its not working, because in the source its &ndash and when I look at the result on the website, its a "long minus" (–). Copying and pasting this long minus into some editor makes it a normal minus (-). I cant split at "-" nor at &ndash, but somehow it must be possible. When I created the article, I just typed "-" (minus), but somewhere it gets converted to – automatically.
Any ideas?
Thanks!
I think I found it. I remember that I have meet the similar problem that when I paste code in my post the quote mark transform to an em-quad one when display to readers.
I found that is in /wp-include/formatting.php line 56 (wordpress ver 3.3.1), it defined some characters need to replace
$static_characters = array_merge( array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'\'', ' (tm)'), $cockney );
$static_replacements = array_merge( array($em_dash, ' ' . $em_dash . ' ', $en_dash, ' ' . $en_dash . ' ', 'xn--', '…', $opening_quote, $closing_quote, ' ™'), $cockneyreplace );
and in line 85 it make an replacement
// This is not a tag, nor is the texturization disabled static strings
$curl = str_replace($static_characters, $static_replacements, $curl);
If you want to split a string at the "-" character, basically you must replace "-" with a space.
Try this:
$string_to_be_stripped = "my-word-test";
$chars = array('-');
$new_string = str_replace($chars, ' ', $string_to_be_stripped);
echo $new_string;
These lines splits the string at the "-". For example, if you have my-word-test, it will echo "my word test". I hope it helps.
For more information about the str_replace function click here.
If you want to do this in a WordPress style, try using filters. I suggest placing these lines in your functions.php file:
add_filter('the_title', function($title) {
$string_to_be_stripped = $title;
$chars = array('-');
$new_string = str_replace($chars, ' ', $string_to_be_stripped);
return $new_string;
})
Now, everytime you use the_title in a loop, the title will be escaped.

PHP line break with file_put_contents()

I can't seem to figure out why the following code doesn't produce a new line in my text file - neither does using \n etc either - any ideas what could be wrong?
$data = $name . ' | ' . $_POST['comment'] . PHP_EOL;
//write to file
$f = file_put_contents('posts.txt', $data, FILE_APPEND);
Are you viewing the text file in an internet browser by any chance?
If you are, the browser will get rid of the newline characters (unless you're using PRE tags).
Try double quotes: $data = $name . ' | ' . $_POST['comment'] . "\n";
Or: $data = "$name | {$_POST['comment']}\n";
Have you tried \r or \n\r ? Just an idea.

Categories