I downloaded GCIDE (GNU Project's publication of CIDE, the Collaborative International Dictionary of English) from its website.
The package contains various XML files. I am running PHP with Apache in my Windows PC. How can I search for a word and its definition in these XML files using PHP?
Your project intrigued me, and thought I might find it useful sometime, so did some research, and found the below code on this page. I ran this php, and currently have a fully functional dictionary in my database!
Here's everything I did to get it up and running (I unzipped the XML files into a folder called XML within the folder that contains these files).
SQL for Table - gcide
CREATE TABLE `gcide` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`word` varchar(255) DEFAULT NULL,
`definition` text,
`pos` varchar(50) DEFAULT NULL,
`fld` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `word` (`word`)
) ENGINE=MyISAM
PHP for gcide XML Import - import_gcide_xml.php
<?php
$connection = mysql_connect('localhost', 'root', '') or die('Could not connect to MySQL database. ' . mysql_error());
$db = mysql_select_db('fiddle',$connection);
mysql_query('TRUNCATE TABLE gcide') or die(mysql_error());
$xml = array('xml/gcide_a.xml', 'xml/gcide_b.xml', 'xml/gcide_c.xml', 'xml/gcide_d.xml', 'xml/gcide_e.xml','xml/gcide_f.xml','xml/gcide_g.xml', 'xml/gcide_h.xml', 'xml/gcide_i.xml', 'xml/gcide_j.xml', 'xml/gcide_k.xml', 'xml/gcide_l.xml', 'xml/gcide_m.xml', 'xml/gcide_n.xml', 'xml/gcide_o.xml', 'xml/gcide_p.xml', 'xml/gcide_q.xml', 'xml/gcide_r.xml', 'xml/gcide_s.xml', 'xml/gcide_t.xml', 'xml/gcide_u.xml', 'xml/gcide_v.xml', 'xml/gcide_w.xml', 'xml/gcide_x.xml', 'xml/gcide_y.xml', 'xml/gcide_z.xml');
$numberoffiles = count($xml);
for ($i = 0; $i <= $numberoffiles-1; $i++) {
$xmlfile = $xml[$i];
// original file contents
$original_file = #file_get_contents($xmlfile);
// if file_get_contents fails to open the link do nothing
if(!$original_file) {}
else {
// find words in original file contents
preg_match_all("/<hw>(.*?)<\/hw>(.*?)<def>(.*?)<\/def>/", $original_file, $results);
$blocks = $results[0];
// traverse blocks array
for ($j = 0; $j <= count($blocks)-1; $j++) {
preg_match_all("/<hw>(.*?)<\/hw>/", $blocks[$j], $wordarray);
$words = $wordarray[0];
$word = addslashes(strip_tags($words[0]));
$word = preg_replace('{-}', ' ', $word);
$word = preg_replace("/[^a-zA-Z0-9\s]/", "", $word);
preg_match_all("/<def>(.*?)<\/def>/", $blocks[$j], $definitionarray);
$definitions = $definitionarray[0];
$definition = addslashes(strip_tags($definitions[0]));
$definition = preg_replace('{-}', ' ', $definition);
$definition = preg_replace("/[^a-zA-Z0-9\s]/", "", $definition);
preg_match_all("/<pos>(.*?)<\/pos>/", $blocks[$j], $posarray);
$poss = $posarray[0];
$pos = addslashes(strip_tags($poss[0]));
$pos = preg_replace('{-}', ' ', $pos);
$pos = preg_replace("/[^a-zA-Z0-9\s]/", "", $pos);
preg_match_all("/<fld>(.*?)<\/fld>/", $blocks[$j], $fldarray);
$flds = $fldarray[0];
$fld = addslashes(strip_tags($flds[0]));
$fld = preg_replace('{-}', ' ', $fld);
$fld = preg_replace("/[^a-zA-Z0-9\s]/", "", $fld);
$insertsql = "INSERT INTO gcide (word, definition, pos, fld) VALUES ('$word', '$definition', '$pos', '$fld')";
$insertresult = mysql_query($insertsql) or die(mysql_error());
echo $word. " " . $definition ."\n";
}
}
}
echo 'Done!';
?>
CSS For Search Page - gcide.css
body{ font-family:Arial, Helvetica, sans-serif; }
#search_box { padding:4px; border:solid 1px #666666; margin-bottom:15px; width:300px; height:30px; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px; }
#search_results { display:none;}
.word { font-weight:bold; }
.found { font-weight: bold; }
dl { font-family:serif;}
dt { font-weight:bold;}
dd { font-weight:normal;}
.pos { font-weight: normal;}
.fld { margin-right:10px;}
HTML for Search Page - index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHP, jQuery search of GCIDE</title>
<link href="gcide.css" rel="stylesheet" type="text/css"/>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
$("#search_box").keyup(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "gcide_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#search_results").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="ui-widget-content" style="padding:10px;">
<input id="search_box" class='search_box' type="text" />
<div id="search_results">Search results for <span class="word"></span></div>
<dl id="results"></dl>
</div>
</body>
</html>
PHP for jQuery Search - gcide_search.php
<?php
if (isset($_POST['search'])) {
$db = new pdo("mysql:host=localhost;dbname=fiddle", "root", "");
// never trust what user wrote! We must ALWAYS sanitize user input
$word = mysql_real_escape_string($_POST['search']);
$query = "SELECT * FROM gcide WHERE word LIKE '" . $word . "%' ORDER BY word LIMIT 10";
$result = $db->query($query);
$end_result = '';
if ($result) {
while ( $r = $result->fetch(PDO::FETCH_ASSOC) ) {
$end_result .= '<dt>' . $r['word'];
if($r['pos']) $end_result .= ', <span class="pos">'.$r['pos'].'</span>';
$end_result .= '</dt>';
$end_result .= '<dd>';
if($r['fld']) $end_result .= '<span class="fld">('.$r['fld'].')</span>';
$end_result .= $r['definition'];
$end_result .= '</dd>';
}
}
if(!$end_result) {
$end_result = '<dt><div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;">
<p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>
No results found.</p>
</div></dt>';
}
echo $end_result;
}
?>
I happend to stumble across this PHP and AJAX example a little while back - it might get you pointed in the right direction, but with that much data, you might want to consider importing it into a database and use it's searching capabilities- that's what they're designed for, whereas performance will likely be an issue chugging through that much plain text of an XML file. Take a look at this answer for XML importing. Also found this SO answer about importing GCIDE XML.
Related
I have created a simple CSS editing/optimizing system in a WordPress plugin. Basically, the CSS files are stored in a folder. They are accessed to edit though a selection box using jQuery.
HTML
# edit stylesheet
echo '<div id="editStyles" class="s8w-hide">';
echo '<h2>Edit a Stylesheet</h2>';
echo '<form action="" method="post">';
# file name
echo '<div class="s8w-row">';
echo '<div class="s8w-col_12">';
echo '<select id="getStylesheeteEdit" name="filename" class="s8w-expand">';
echo '<option value="">Select Stylesheet to Edit</option>';
foreach(glob(S8W_CSS_GEN . 'common/*.css') as $file) {
$filename = basename($file);
echo '<option value="'.$filename.'">'.$filename.'</option>';
}
echo '</select>';
echo '</div>';
echo '</div>';
# styles
echo '<div class="s8w-row">';
echo '<div class="s8w-col_12">';
echo '<textarea id="showEditStyles" name="styles" class="s8w-expand" style="height: 350px;"></textarea>';
echo '</div>';
echo '</div>';
echo '<div class="s8w-row">';
echo '<div class="s8w-col_12 s8w-center">';
echo '<input type="submit" name="edit_stylesheet" class="s8w navy tiny-radius" value="Edit this Stylesheet">';
echo '</div>';
echo '</div>';
echo '</form>';
jQuery
This jQuery added slashes so I added the commented out line but it did not remove them.
/* GET STYLESHEET TO EDIT
----------------------------------------------------- */
$( "#getStylesheeteEdit" ).change(function() {
var which = $(this).val();
var file = 'https://s8w.org/wp-content/plugins/IDCCST/css/generator/common/' + which;
$.get(file, function(data) {
//data.replace('\\','');
$('#showEditStyles').val(data);
});
});
parsing php
I added stripslashes here which did remove the slashes.
/* EDIT STYLESHEET
--------------------------------------------------------- */
if(array_key_exists('edit_stylesheet',$_POST)){
$filename = $_POST['filename'];
$styles = stripslashes($_POST['styles']);
# update styles
file_put_contents(S8W_CSS_GEN . 'common/'.$filename, $styles);
# parse stylesheets
$msg = 'The stylesheet: '.$filename.' and the S8W Stylesheet have been updated.';
parseStyles($msg);
}
parseStyles($msg); minimizes and writes single style sheet.
<?php
function parseStyles($msg){
/* admin styles
-------------------------------------- */
foreach(glob(S8W_CSS_GEN . 'admin/*.css') as $file) {
$admin_code .= file_get_contents($file);
$prep_styles = file_get_contents($file);
$prep_styles = str_replace("/*","~",$prep_styles);
$prep_styles = str_replace("*/","~",$prep_styles);
preg_match_all("'~(.*?)~'si", $prep_styles, $match);
foreach($match[1] as $val) {
$this_comment = '~'.$val.'~';
$prep_styles = str_replace($this_comment,"",$prep_styles);
}
//$prep_styles = str_replace('\"','"',$prep_styles);
$prep_styles = str_replace("\r","",$prep_styles);
$prep_styles = str_replace("\n","",$prep_styles);
$prep_styles = str_replace("\t","",$prep_styles);
$admin_styles .= $prep_styles;
}
/* common styles
-------------------------------------- */
foreach(glob(S8W_CSS_GEN . 'common/*.css') as $file) {
$common_code .= file_get_contents($file);
$prep_styles = file_get_contents($file);
$prep_styles = str_replace("/*","~",$prep_styles);
$prep_styles = str_replace("*/","~",$prep_styles);
preg_match_all("'~(.*?)~'si", $prep_styles, $match);
foreach($match[1] as $val) {
$this_comment = '~'.$val.'~';
$prep_styles = str_replace($this_comment,"",$prep_styles);
}
//$prep_styles = str_replace('\"','"',$prep_styles);
$prep_styles = str_replace("\r","",$prep_styles);
$prep_styles = str_replace("\n","",$prep_styles);
$prep_styles = str_replace("\t","",$prep_styles);
$common_styles .= $prep_styles;
}
# write admin styles
$admin_styles = $common_styles.$admin_styles;
file_put_contents(S8W_CSS . 's8w-admin-styles.css', $admin_styles);
# write admin styles
$admin_readable = $common_code.$admin_code;
file_put_contents(S8W_CSS_GEN . 'readable-admin.css', $admin_readable);
$common_styles = $common_styles;
# write admin styles
file_put_contents(S8W_CSS . 's8w-styles.css', $common_styles);
# write admin styles
$common_readable = $common_code;
file_put_contents(S8W_CSS_GEN . 'readable.css', $common_readable);
echo '<Script language="javascript">alert("'.$msg.'");</script>';
}
All of this code works great if the styles do not have double quote. The file is called to the editing textarea and parses perfectly and write the minimized file. However, if the styles have double quotes:
CSS Example with Double Quotes
/* BUTTONS
------------------------------------------------------------------- */
button.s8w,
a.button.s8w,
input[type="submit"].s8w,
input[type="button"].s8w {
position:relative;
top:0;
left:0;
padding:10px 15px;
line-height:100%;
vertical-align: middle;
cursor: pointer;
overflow:visible;
font-weight:normal;
font-size:16px;
text-decoration:none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
display:inline-block;
zoom:1;
background: #fcfcfc;
color:#666;
border:1px solid #cccccc;
text-align: center;
border-radius: 0;
}
The file will save and be minimized. But when the file is called though jQuery, though the edits are saved to the file, the new edits do not render in the textarea and as a result are lost if the file is saved once again. Hope I was able to explain the problem clearly. Any help or thoughts are appreciated.
While I am still not sure what was happening, the problem was in this jQuery:
/* GET STYLESHEET TO EDIT
----------------------------------------------------- */
$( "#getStylesheeteEdit" ).change(function() {
var which = $(this).val();
var file = 'https://s8w.org/wp-content/plugins/IDCCST/css/generator/common/' + which;
$.get(file, function(data) {
//data.replace('\\','');
$('#showEditStyles').val(data);
});
});
When a css file was edited the edits would be saved and parsed through the minimizer php, but the above jQuery would not pick up the edits on the saved file when it was reselected. Have no idea as to why?
I was able to resolve the issue by changing the jQuery to:
$( "#getStylesheeteEdit" ).change(function() {
var which = $(this).val();
var url = 'https://s8w.org/wp-content/plugins/IDCCST/css/generator/get-stylsheet.php';
var postit = $.post( url, {which:which});
postit.done(function( data ) {$('#showEditStyles').val(data);});
});
and adding a php parse file with only one line of code to be able to make use of file_get_contents() instead using jQuery to get the contents of the desired css file:
<?php
$file = 'common/'.$_POST['which']; echo file_get_contents($file);
Here i want to do read the xl file in php,here i displayed all datas that means in xl file i have four columns called Title,Url,Visitors,Accesses.but for me don't want like this , i want only title name how can do this ? View my answer
<?php
include 'excel_reader.php'; // include the class
// creates an object instance of the class, and read the excel file data
$excel = new PhpExcelReader;
$excel->read('test.xls');
function sheetData($sheet) {
$re = '<table>'; // starts html table
$row = 1;
while($row <= $sheet['numRows']) {
$re .= "<tr>\n";
$column = 1;
$cell = isset($sheet['cells'][$row][1]) ? $sheet['cells'][$row][1] : '';
$re .= " <td>$cell</td>\n";
$re .= "</tr>\n";
$row++;
}
return $re .'</table>';// ends and returns the html table
}
$nr_sheets = count($excel->sheets);// gets the number of sheets
$excel_data = ''; // to store the the html tables with data of each sheet
// traverses the number of sheets and sets html table with each sheet data in $excel_data
for($i=0; $i<$nr_sheets; $i++) {
//$excel_data .= '<h4>Sheet '. ($i + 1) .' (<em>'. $excel->boundsheets[$i]['name'] .'</em>)</h4>'. sheetData($excel->sheets[$i]) .'<br/>';
$excel_data .= sheetData($excel->sheets[$i]) .'<br/>';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example PHP Excel Reader</title>
<style type="text/css">
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<?php
// displays tables with excel file data
echo $excel_data;
?>
</body>
</html>
By observing the $sheet array you will get Title at the position of 4,1 as follows.
By changing this line as shown
$cell = isset($sheet['cells'][4][1]) ? $sheet['cells'][4][1] : '';
But it looks like you have copied this code from somewhere. It is hard to identify your need and modify it. Change the code as per your requirement and if any error occurs then post your question on SO
as per your requirement your sheetData function should be like this
function sheetData($sheet) {
$re = '<table>'; // starts html table
$x = 1;
while($x <= $sheet['numRows']) {
$re .= "<tr>\n";
$cell = isset($sheet['cells'][$x][1]) ? $sheet['cells'][$x][1] : '';
if($cell != 'Title'){ // check for title here
$re .= " <td>$cell</td>\n";
$re .= "</tr>\n";
}
$x++;
}
return $re .'</table>'; // ends and returns the html table
}
Suppose someone enters a string in a textarea like this
"The best search engine is www.google.com."
or maybe
"The best search engine is https://www.google.co.in/?gfe_rd=cr&ei=FLB1U4HHG6aJ8Qfc1YHIBA."
Then i want to highlight the link as stackoverflow does.
And also i want to file_get_contents to get one image , a short description and title of the page.
Most probably i wanna check if the string contains a url or not -> two times.
On keyup of textarea using jQuery and therefore using the
get_file_contents
When the string is recieved by php.
Possibly how can i do this?
UPDATE
function parseHyperlinks($text) {
// The Regular Expression filter
$reg_exUrl1 = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exUrl2 = "/[\w\d\.]+\.(com|org|ca|net|uk)/";
// The Text you want to filter for urls
// Check if there is a url in the text
if(preg_match($reg_exUrl1, $text, $url)) {
// make the urls hyper links
return preg_replace($reg_exUrl1, "<a class=\"content-link link\" href=\"{$url[0]}\">{$url[0]}</a> ", $text);
} else if(preg_match($reg_exUrl2, $text, $url)){
return preg_replace($reg_exUrl2, "<a class=\"content-link link\" href=\"{$url[0]}\">{$url[0]}</a> ", $text);
}else{
// if no urls in the text just return the text
return $text;
}
}
This works only if $str='www.google.com is the best' or $str='http://www.google.com is best' but not if $str='http://stackoverflow.com/ and www.google.com is the best'
First off you create the html then you need to an AJAX to request to the server. Consider this sample codes:
HTML/jQuery:
<!-- instead of textarea, you could use an editable div for styling highlights, or if you want, just use a plugin -->
<div id="textarea"
style="
font-family: monospace;
white-space: pre;
width: 300px;
height: 200px;
border: 1px solid #ccc;
padding: 5px;">For more tech stuff, check out http://www.tomshardware.com/ for news and updates.</div><br/>
<button type="button" id="scrape_site">Scrape</button><br/><br/>
<!-- i just used a button to hook up the scraping, you can just bind it on a keyup/keydown. -->
<div id="site_output" style="width: 500px;">
<label>Site: <p id="site" style="background-color: gray;"></p></label>
<label>Title: <p id="title" style="background-color: gray;"></p></label>
<label>Description: <p id="description" style="background-color: gray;"></p></label>
<label>Image: <div id="site_image"></div></label>
</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#scrape_site').on('click', function(){
var value = $.trim($('#textarea').text());
$('#site, #title, #description').text('');
$('#site_image').empty();
$.ajax({
url: 'index.php', // or you php that will process the text
type: 'POST',
data: {scrape: true, text: value},
dataType: 'JSON',
success: function(response) {
$('#site').text(response.url);
$('#title').text(response.title);
$('#description').text(response.description);
$('#site_image').html('<img src="'+response.src+'" id="site_image" />');
}
});
});
// you can use an editable div so that it can be styled,
// theres to much code already in the answer, you can just get a highlighter plugin to ease your pain
$('#textarea').each(function(){
this.contentEditable = true;
});
});
</script>
And on your php that will process, in this case (index.php):
if(isset($_POST['scrape'])) {
$text = $_POST['text'];
// EXTRACT URL
$reg_exurl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
preg_match_all($reg_exurl, $text, $matches);
$usedPatterns = array();
$url = '';
foreach($matches[0] as $pattern){
if(!array_key_exists($pattern, $usedPatterns)){
$usedPatterns[$pattern] = true;
$url = $pattern;
}
}
// EXTRACT VALUES (scraping of title and descriptions)
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXPath($doc);
$title = $xpath->query('//title')->item(0)->nodeValue;
$description = $xpath->query('/html/head/meta[#name="description"]/#content');
if ($description->length == 0) {
$description = "No description meta tag :(";
// Found one or more descriptions, loop over them
} else {
foreach ($description as $info) {
$description = $info->value . PHP_EOL;
}
}
$data['description'] = $description;
$data['title'] = $title;
$data['url'] = $url;
// SCRAPING OF IMAGE (the weirdest part)
$image_found = false;
$data['src'] = '';
$images = array();
// get all possible images and this is a little BIT TOUGH
// check for og:image (facebook), some sites have this, so first lets take a look on this meta
$facebook_ogimage = $xpath->query("/html/head/meta[#property='og:image']/#content");
foreach($facebook_ogimage as $ogimage) {
$data['src'] = $ogimage->nodeValue;
$image_found = true;
}
// desperation search (get images)
if(!$image_found) {
$image_list = $xpath->query("//img[#src]");
for($i=0;$i<$image_list->length; $i++){
if(strpos($image_list->item($i)->getAttribute("src"), 'ad') === false) {
$images[] = $image_list->item($i)->getAttribute("src");
}
}
if(count($images) > 0) {
// if at least one, get it
$data['src'] = $images[0];
}
}
echo json_encode($data);
exit;
}
?>
Note: Although this is not perfect, you can just use this as a reference to just improved on it and make it more dynamic as you could.
I have this code.
<html>
<head>
<style type="text/css">
body{background:#666666;}
div{border:1px solid red;}
</style>
</head>
<body>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM hi");
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
mysql_close($con);
?>
</body>
</html>
the above code works.
now, I want to insert this
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
into the specified div or other element in the html, example, i will insert this
echo '<img src="'.$row['name'].'" />';
into the html element .
I dont know how to do this, please help me. Thanks
Juliver
if yo want to place in an div like
i have same work and i do it like
<div id="content>
<?php
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
?>
</div>
The only things I can think of are
including files
replacing elements within files using preg_match_all
using assigned variables
I have recently been using str_replace and setting text in the HTML portion like so
{{TEXT_TO_REPLACE}}
using file_get_contents() you can grab html data and then organise it how you like.
here is a demo
myReplacementCodeFunction(){
$text = '<img src="'.$row['name'].'" />';
$text .= "<div>".$row['name']."</div>";
$text .= "<div>".$row['title']."</div>";
$text .= "<div>".$row['description']."</div>";
$text .= "<div>".$row['link']."</div>";
$text .= "<br />";
return $text;
}
$htmlContents = file_get_contents("myhtmlfile.html");
$htmlContents = str_replace("{{TEXT_TO_REPLACE}}", myReplacementCodeFunction(), $htmlContents);
echo $htmlContents;
and now a demo html file:
<html>
<head>
<style type="text/css">
body{background:#666666;}
div{border:1px solid red;}
</style>
</head>
<body>
{{TEXT_TO_REPLACE}}
</body>
</html>
You can write the php code in another file and include it in the proper place where you want it.
AJAX is also used to display HTML content that is formed by PHP into a specified HTML tag.
Using jQuery:
$.ajax({url: "test.php"}).done(function( html ) {
$("#results").append(html);
});
Above code will execute test.php and result will be displayed in the element with id results.
There is no way that you can do it in PHP when HTML is already generated. What you can do is to use JavaScript or jQuery:
document.getElementById('//ID//').innerHTML="HTML CODE";
If you have to do it when your URI changes you can get the URI and then split it and then insert the HTML in script dynamically:
var url = document.URL;
// to get url and then use split() to check the parameter
refer to the basic.
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
there is no way to specifically target an element with php, you can either embed the php code between a div tag or use jquery which would be longer.
You can repeat it by fetching again the data
while($row = mysql_fetch_assoc($result)){
//another html element
<div>$row['name']</div>
<div>$row['title']</div>
//and so on
}
or you need to put it on the variable and call display it again on other html element
$name = $row['name'];
$title = $row['title']
//and so on
then put it on the other element, but if you want to call all the data of each id, you need to do the first code
Have you tried this?:
$string = '';
while($row = mysql_fetch_array($result))
{
//this will combine all the results into one string
$string .= '<img src="'.$row['name'].'" />
<div>'.$row['name'].'</div>
<div>'.$row['title'].'</div>
<div>'.$row['description'].'</div>
<div>'.$row['link'].'</div><br />';
//or this will add the individual result in an array
/*
$yourHtml[] = $row;
*/
}
then you echo the $tring to the place you want it to be
<div id="place_here">
<?php echo $string; ?>
<?php
//or
/*
echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
*/
?>
</div>
Well from your code its clear that $row['name'] is the location of the image on the file, try including the div tag like this
echo '<div>' .$row['name']. '</div>' ;
and do the same for others, let me know if it works because you said that one snippet of your code is giving the desired result so try this and if the div has some class specifier then do this
echo '<div class="whatever_it_is">' . $row['name'] . '</div'> ;
You have to put div with single quotation around it. ' ' the Div must be in the middle of single quotation . i'm gonna clear it with one example :
<?php
echo '<div id="output">'."Identify".'<br>'.'<br>';
echo 'Welcome '."$name";
echo "<br>";
echo 'Web Mail: '."$email";
echo "<br>";
echo 'Department of '."$dep";
echo "<br>";
echo "$maj";
'</div>'
?>
hope be useful.
I use this or similar code to inject PHP messages into a fixed DIV positioned in front of other elements (z-index: 9999) just for convenience at the development stage.
Each PHP message passes into my 'custom_message()' function and is further conveyed into the innard of preformatted DIV created by echoed JS.
There can be as many as it gets, all put inside that fixed DIV, one under the other.
<style>
#php_messages {
position: fixed;
left: 0;
top: 0;
z-index: 9999;
}
.php_message {
background-color: #333;
border: red solid 1px;
color: white;
font-family: "Courier New", Courier, monospace;
margin: 1em;
padding: 1em;
}
</style>
<div id="php_messages"></div>
<?php
function custom_message($output) {
echo
'
<script>
var
el = document.createElement("DIV");
el.classList.add("php_message");
el.innerHTML = \''.$output.'\';
document.getElementById("php_messages").appendChild(el);
</script>
';
}
?>
Is there any already done php class that could parse a link like Facebook, Google+ or Digg does? To get the title, some text and images from the page? :)
Thanks
Here is some code I pinched from sitepoint.com. I have used it a few times and it seems to work nicely...
<?php
define( 'LINK_LIMIT', 30 );
define( 'LINK_FORMAT', '%s' );
function parse_links ( $m ){
$href = $name = html_entity_decode($m[0]);
if ( strpos( $href, '://' ) === false ) {
$href = 'http://' . $href;
}
if( strlen($name) > LINK_LIMIT ) {
$k = ( LINK_LIMIT - 3 ) >> 1;
$name = substr( $name, 0, $k ) . '...' . substr( $name, -$k );
}
return sprintf( LINK_FORMAT, htmlentities($href), htmlentities($name) );
}
$s = 'Here is a text - www.ellehauge.net - it has some links with e.g. comma, www.one.com,in it. Some links look like this: http://mail.google.com - mostly they end with aspace or carriage return www.unis.no<br /> - but they may also end with a period: http://ellehauge.net. You may even putthe links in brackets (www.skred-svalbard.no) (http://one.com).From time to time, links use a secure protocol like https://gmail.com |This.one.is.a.trick. Sub-domaines: http://test.ellehauge.net |www.test.ellehauge.net | Files: www.unis.no/photo.jpg |Vars: www.unis.no?one=1&~two=2 | No.: www.unis2_check.no/doc_under_score.php |www3.one.com | another tricky one:http://ellehauge.net/cv_by_id.php?id%5B%5D=105&id%5B%5D=6&id%5B%5D=100';
$reg = '~((?:https?://|www\d*\.)\S+[-\w+&##/%=\~|])~';
print preg_replace_callback( $reg, 'parse_links', $s );
?>
This looks like something you could use:
http://www.redsunsoft.com/2011/01/parse-link-like-facebook-with-jquery-and-php/
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>body
{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
}
#contentbox
{
width:458px; height:50px;
border:solid 2px #dedede;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
margin-bottom:6px;
}
.img
{
float:left; width:150px; margin-right:10px;
text-align:center;
}
#linkbox
{
border:solid 2px #dedede; min-height:50px; padding:15px;
display:none;
}</style>
<script type="text/javascript">
$(document).ready(function()
{
$("#contentbox").keyup(function()
{
var content=$(this).val();
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
// Filtering URL from the content using regular expressions
var url= content.match(urlRegex);
if(url.length>0)
{
$("#linkbox").slideDown('show');
$("#linkbox").html("<img src='link_loader.gif'>");
// Getting cross domain data
$.get("urlget.php?url="+url,function(response)
{
// Loading <title></title>data
var title=(/<title>(.*?)<\/title>/m).exec(response)[1];
// Loading first .png image src='' data
var logo=(/src='(.*?).png'/m).exec(response)[1];
$("#linkbox").html("<img src='"+logo+".png' class='img'/><div><b>"+title+"</b><br/>"+url)
});
}
return false;
});
});
//HTML Code
<textarea id="contentbox"></textarea>
<div id="linkbox"></div>
</script>
urlget.php
<?php
if($_GET['url'])
{
$url=$_GET['url'];
echo file_get_contents($url);
}
?>
source