views:

53

answers:

2

Hi, I am using a simple script on my PHP webpage to decode and output JSON as text. However, what ever I try I can't get it to wordwrap the output.

$file = file_get_contents('sample.txt');
$out = (json_decode($file));
echo $out->mainText;

How can I get this script to wordwrap at 600 characters without chopping words in half?

If possible, can you show me the whole script please as I am slowly learning.

Thanks

+3  A: 

have a look at the wordwrap function in php.

oedo
A: 

I won't write the code for you, but what you could do is cut of the text to 600 characters, which you do using substr and then see if the last character is a symbol like space, comma, period or whatever. If it isn't, try it at 599, then 598 etc. etc.

It's a better way to learn, by trying it yourself.

(added) Ah I might have misread the question after seeing the other comment, in which case the wordwrap function that oedo mentioned might be all you need...

CharlesLeaf
I have tried a couple of hundred ways to do this but each time it either fails or ends up in some sort of syntax error. I have tried even using tables but the text just heads west or disappears altogether. Thanks all the same.
Gary
@Gary, before I say anything else: Do you want to cut the text at 600 characters without breaking words, or actually wrap it with a symbol (a newline or something)? Because if it's the latter, you should still look at PHP's `wordwrap` function, especially the last argument called `$cut` and what it does; namely what you want by default. http://php.net/manual/en/function.wordwrap.php
CharlesLeaf
Hi Charles,Would prefer to cut the text at 600 characters without breaking words. I think that I may have found the solution.//<?php$file = file_get_contents('warntest.txt'); $out = (json_decode($file)); echo $out->issuedAt;//?>//<?PHP echo wordwrap($out->mainText, 100, "<br>\n"); //?>What it is is a 3 part file, issuedate, maintext and pic. I now realise where I was going wrong by not telling it what file/text to wrap.
Gary