My JSON result http://daysof.me/lowyat/list.php
What I did:
$num = 0;
$array = array();
foreach($rows as $go){
if($num == count($rows)-1){break;}
$reply = $go->find('td',3)->plaintext;//replies
$starter = $go->find('td',4)->plaintext;//starter
$views = $go->find('td',5)->plaintext;//views
$action = $go->find('td',6)->plaintext;//last action
$desc = $go->find('td',2)->find('div div',2)->plaintext;//description
$title = $go->find('td',2)->find('div div a',0)->plaintext;//topic name
$link = $go->find('td',2)->find('div div a',0)->href;
$array[]= array(
'title'=>$title,
'desc'=>$desc,
'starter'=>trim($starter),
'replies'=>trim($reply),
'url'=>'https://forum.lowyat.net'.$link
);
$num ++;
}
echo json_encode($array);
You'll see some single quote been turned into " and ampersand gave strange code.
How can I escape that? I tried 'title'=>htmlentities($title) still no luck with that.
Related
I have been trying to print an output using json_encode, the code is below:
<?
$lid = $_GET['last_id'];
$sql = "SELECT * FROM tbl_posts WHERE id < $lid ORDER BY id DESC LIMIT 10";
$result = mysqli_query($con,$sql);
$json = include('datam.php');
echo json_encode($json);
?>
Here is the datam.php file:
<?
$count = 0;
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$likes = $row['likes'];
$dislikes = $row['dislikes'];
$text = $row['text'];
$text = htmlspecialchars($text);
$title = substr($text, 0, 50);
$title = preg_replace('~[^\\pL\d]+~u', '-', $title);
$title = trim($title, '-');
$title = strtolower($title);
$title = preg_replace('~[^-\w]+~', '', $title);
if(empty($title)) {
$title = "no-title";
}
$cat = $row['cat'];
$cat = strtolower($cat);
$cat = str_replace(" ","-",$cat);
$ccat = str_replace("-"," ",$cat);
$ccat = ucwords($ccat);
$by = $row['uid'];
$dt = $row['date'];
$tm = $row['time'];
$time = strtotime("$dt $tm");
$nsfw = $row['nsfw'];
if ($nsfw == 1)
$isnsfw = '<span class="nsfw">NSFW</span>';
else
$isnsfw = "";
// Time Ago
// Get OP
$suser = "SELECT * FROM tbl_users WHERE id = $by";
$muser = mysqli_query($con,$suser);
$guser = mysqli_fetch_array($muser);
$byuser = $guser['user'];
$byuser = strtolower($byuser);
$byuser = str_replace(" ","-",$byuser);
$cbyuser = str_replace("-"," ",$byuser);
$cbyuser = ucwords($cbyuser);
// WhatsApp Link
$wm = preg_replace("/\n/", "%0A", $text);
if($count == 5 && $cnsfw == 0) {
include "adapp.php";
}
echo '<div class="box" id="'.$id.'"><div class="t">Posted by '.$cbyuser.' in '.$ccat.' '.ago($time).' ago</div><div class="m">'.$text.'</div><div class="m"><span class="col-3"><span class="likes">'.$likes.' Likes</span></span><span class="col-3"><span class="dislikes">'.$dislikes.' Dislikes</span></span><span class="col-3">'.$isnsfw.'</span></div><div class="b"><span class="col-5 l bbox"><img src="/img/like.png" /></span><span class="col-5 l bbox"><img src="/img/dislike.png" /></span><span class="col-5 l bbox"><img src="/img/comment.png" /></span><span class="col-5 l bbox"><a rel="nofollow" href="whatsapp://send?text=http://whatsappstatus.in/msg/'.$id.'%0A'.$wm.'"><img src="/img/whatsapp.png" /></a></span><span class="col-5 l bbox"><img src="/img/options.png" /></span></div><div class="clr"></div></div>';
$count++;
}
?>
Using this code, all the output appears as expected but, at the end of each output, there is unexpected output 1 which has no source of origin.
Every time this code executes, it gives an unexpected 1 at the end and I can't seem to find where it is coming from.
Here is the picture of sample output:
You can visit this URL to check it: http://funpd.com/messages1
When using
$json = include('datam.php');
In your datam.php you should return the value of the data you want assigning to $json rather than echoing it out. The echo in the datam.php is code which is displaying the data and the 1 is the value being assigned to $json (which is the value returned by your datam.php page).
You can test this by commenting out the echo in the sub page and you should just see the value 1 being displayed.
It may be the easiest solution looking at your code to just include this sub-page and not assign the value to $json, but you may have a reason for json encoding the return value.
Update:
To batch data up, build an array of data. At the top
$output = [];
After your echo - build an array of the results and add it to output array...
$output[] = [$id, $byuser, $cbyuser, ...];
(You will need to complete this with all of the fields you need)
And at the end
return $output;
This will pass all the data back to the calling page.
So I have attempted to get anything with a #texthere t change to a link so i can navigate them to the hash page of that specific hash.
With the code I have I just keep getting 'undefined' back. Can someone please take a look and point out where I am going wrong.
$json = array(
'userpost' => array()
);
$row = mysqli_fetch_assoc($check1);
$posts = array();
$posts['num'] = $num;
$posts['streamitem_id'] = $row['streamitem_id'];
$autoembed = new AutoEmbed();
$posts['streamitem_content'] = $autoembed->parse($row['streamitem_content']);
$regex = "/#(\w+)/";
$string=$row['streamitem_content'];
$string = preg_replace($regex, '$1', $string);
$posts['streamitem_content']=json_decode($string);
$posts['streamitem_creator'] = $row['streamitem_creator'];
$posts['streamitem_timestamp'] = $row['streamitem_timestamp'];
$posts['username'] = $row['username'];
$posts['id'] = $row['id'];
$posts['first'] = $row['first'];
$posts['middle'] = $row['middle'];
$posts['last'] = $row['last'];
$json['userpost'][] = $posts;
echo json_encode($json);
Okay this is what I've done to fix the issue. no decoding needed and that is what was causing the issue.
$regex = "/#(\w+)/";
$posts['streamitem_content'] = $row['streamitem_content'];
$posts['streamitem_content'] = preg_replace($regex, "
<a href='hash.php?tag=$1'>$1</a>", $posts['streamitem_content'] );
Hello I am having trouble with array to string conversion in the following script.
The problem is on the top if statement. For some reason it works fine in the else statement underneath but I keep getting a array to string conversion error when submitting my form and I'm not sure why it works before submitting the form but not after.
The problem is apparently in the first
$content[] = array.
It just returns the word array for $video variable. So where it states the videoid in data-videoID="" it just comes up as data-videoId="Array". Everything esle comes up fine. This would be on line 12 and 13. Here is the code I am using. Im sure it probably something simple that I am overlooking because I am in no way as experienced with php as I probably should be. I have looked over other posts and have tried taking off the brackets and several other things but still cant figure it out. Like I said it works fine if I take out the if statement and just use the else statement. Here is the code.
if(isset($_GET['q'])) {
$keyword_q = $_GET['q'];
$keyword = preg_replace('/\s+/', '/', $keyword_q);
$file = file_get_contents("https://www.googleapis.com/youtube/v3/search?videoEmbeddable=true&videoType=any&part=id%2Csnippet&q=$keyword&videoSyndicated=true&type=video&maxResults=50&key=$key");
$decoded = json_decode($file, true);
$entries = $decoded['items'];
if (!empty($entries)) {
for($i=0; $i<count($entries); $i++) {
$thumb = $entries[$i]['snippet']['thumbnails']['medium']['url'];
$videotitle = $entries[$i]['snippet']['title'];
$videodescription = $entries[$i]['snippet']['description'];
$video = $entries[$i]['id'];
$content[] = "<li><a href='#' data-videoID='$video' class='video-link'><img src='$thumb' alt='Play Video'></a><h3 class='video-title'>$videotitle</h3><p class='video-description'>$videodescription</p></li>";
}
}
$videos = "";
if (!empty($content)) {
foreach($content as $thumb){
$videos .= "$thumb";
}
}
}
else {
$filefeatured = file_get_contents("https://www.googleapis.com/youtube/v3/videos?chart=mostPopular&part=snippet&maxResults=30&key=$key");
$decoded = json_decode($filefeatured, true);
$entries = $decoded['items'];
if (!empty($entries)) {
for($i=0; $i<count($entries); $i++) {
$thumb = $entries[$i]['snippet']['thumbnails']['medium']['url'];
$videotitle = $entries[$i]['snippet']['title'];
$videodescription = $entries[$i]['snippet']['description'];
$video = $entries[$i]['id'];
$content[]= "<li><a href='#' data-videoID='$video' class='video-link'><img src='$thumb' alt='Play Video'></a><h3 class='video-title'>$videotitle</h3><p class='video-description'>$videodescription</p></li>";
}
}
$videos = "";
if (!empty($content)) {
foreach($content as $thumb){
$videos .= "$thumb";
}
}
}
<?php
$userName = array();
$tutorial = array();
$myFile = "students.txt";
$fh = fopen($myFile,'r');
while( !feof($myFile) ){
$userName[] = array(fgets($fh));//Save first line content
$tutorial[] = array(fgets($fh));//Save second line content
}
fclose($myFile);
echo "$userName";
echo "$tutorial";
?>
and my students.txt content
dasdsa
A
asdasd
D
How to read that and store into different array and print them out
your code should work as expected. I assume you're bit confused with echo "$userName"; output as it displays Array word. try var_dump($userName) instead
Do exactly as you've done, but change
$userName[] = array(fgets($fh));//Save first line content
$tutorial[] = array(fgets($fh));//Save second line content
to
$userName[] = fgets($fh);//Save first line content
$tutorial[] = fgets($fh);//Save second line content
(no need to keep the subitems in their own seperate array)
and print them out by either using print_r, or iterate through them:
for ($i = 0; $i < count($userName); $i++) {
echo $userName[$i] . " - " . $tutorial[$i];
}
$text = file_get_contents('students.txt');
$text = explode("\n",$text);
$output = array();
foreach($text as $line)
{
$output[] = $line;
}
Use function file() in PHP
file — Reads entire file into an array
$array_lines = file('students.txt');
$count = count($array_lines);
$first_arr = array();
$sec_arr = array();
foreach ($array_lines as $i => $line){
if($i%2) $first_arr[] = $line;
else $sec_arr[] = $line;
}
print_r($first_arr);
print_r($sec_arr);
With file() function every line is read as element in array. You can check it with:
print_r($first_arr);
I am trying to store HTML posted from a textarea into a database. I have a textarea inside a form which I have called "message". The PHP code that processes it is:
if(isset($_POST['submit'])){
if(isset($_POST['title']) && isset($_POST['message'])){
$title = $_POST['title'];
$message = $_POST['message'];
if(get_magic_quotes_gpc()){
$title = stripslashes($title);
$message = stripslashes($message);
}
$title = mysql_real_escape_string($title);
$message = mysql_real_escape_string($message);
$q = "INSERT INTO table (title,datetime,text) VALUES ('{$title}',NOW(),'{$message}')";
$rows_affected = $db->exec($q);
if($rows_affected > 0){
echo "<p>Done.</p>";
} else {
echo "<p>Failed. </p>";
}
}
}
The problem I am having is then retrieving this and converting newlines to <br />. Here is what I am doing:
$res = array();
$order = array("\r\n","\n","\r");
$replace = '<br />';
$q = "SELECT title,datetime,text FROM table";
$res = $db->get_all($q);
if($res){
foreach($res as $result){
$result['title'] = stripslashes($result['title']);
$result['text'] = str_replace($order, $replace, stripslashes($result['text']));
}
}
echo "<pre>";
print_r($res);
echo "</pre>";
I just can't get rid of those pesky \r\n's in the message. I have tried changing $order to
$order = array("\\r\\n","\\n","\\r");
// and even
$order = array("\\\r\\\n","\\\n","\\\r");
but nothing seems to work. Any ideas?
if ($res = $db->get_all('SELECT title,datetime,text FROM table')){
foreach ($res as &$result){
$result['text'] = nl2br($result['text']);
}
}
echo "<pre>";
print_r($res);
echo "</pre>";
I did three things:
Remove the stripslashes. They mustn't be there. The slashes mysql_real_escape_string adds are removed when the query is executed.
I used the function nl2br for the new lines. Why write something yourself if it's already built in?
I added a & in front of $result in the foreach loop. If I didn't do this only the shallow copies were modified, not the variables themselves. Thus there wouldn't be any change at all.
For the retrieving of the data you don't need to screw around with str_replace/stripslashes.
$res = array();
$q = "SELECT title,datetime,text FROM table";
$res = $db->get_all($q);
if($res){
foreach($res as &$result){
$result['title'] = $result['title']; // Don't see the reason for stripslashes here
$result['text'] = nl2br($result['text']);
}
}
echo "<pre>";
print_r($res);
echo "</pre>";
Use nl2br to convert your \n to proper HTML line breaks. (Note: If you want to show the text inside of a textarea again, e.g. for editing, you need to output the "text" as-is). The only thing that you would want to do is use strip_tags to prevent HTML from being inserted into your output.
more usual way of what nikic did
foreach ($data as $key => $row){
$data[$key]['text'] = nl2br($row['text']);
}
you did overwrite your temporary $result variable, while you have to write modified variable back into array.
and give our variables sensible names.
Also, consider to use htmlspecialchars() if it's user supplied text.