How can I get the principal image from MediaWiki API? - php

Hello I'm using Curl to get information from Wikipedia,and I want to receive only information about the principal image,I don't want to receive all images of an article..
For example..
If I want to get info about all images of the English Language (http://en.wikipedia.org/wiki/English_language) I should go to this URL:
http://en.wikipedia.org/w/api.php?action=query&titles=English_Language&prop=images
but I receive flags of countries where people speak English in XML:
<?xml version="1.0"?> <api> <query>
<normalized>
<n from="English_language" to="English language" />
</normalized>
<pages>
<page pageid="8569916" ns="0" title="English language">
<images>
<im ns="6" title="File:Anglospeak(800px)Countries.png" />
<im ns="6" title="File:Anglospeak.svg" />
<im ns="6" title="File:Circle frame.svg" />
<im ns="6" title="File:Commons-logo.svg" />
<im ns="6" title="File:Flag of Argentina.svg" />
<im ns="6" title="File:Flag of Aruba.svg" />
<im ns="6" title="File:Flag of Australia.svg" />
<im ns="6" title="File:Flag of Bolivia.svg" />
<im ns="6" title="File:Flag of Brazil.svg" />
<im ns="6" title="File:Flag of Canada.svg" />
I only want the information about the principal image.

There's news! (from 2014)
A new extension, PageImages, is available and also got already installed on the Wikimedia wikis.
Instead of prop=images, use prop=pageimages, and you'll get a pageimage attribute and a <thumbnail> child node for each <page> element.
Admittedly, it's not guaranteed to give the best results, but in your example (English Language) it works well and only yields the map of the geographic distribution, not all the flags.
Also, the OpenSearch API does return an <image> in it's xml representation, but this API is not usable with lists and cannot be combine with the Query API.

This is how I got it working...
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&format=json&callback=?", {
titles: "India",
prop: "pageimages",
pithumbsize: 150
},
function(data) {
var source = "";
var imageUrl = GetAttributeValue(data.query.pages);
if (imageUrl == "") {
$("#wiki").append("<div>No image found</div>");
} else {
var img = "<img src=\"" + imageUrl + "\">"
$("#wiki").append(img);
}
}
);
function GetAttributeValue(data) {
var urli = "";
for (var key in data) {
if (data[key].thumbnail != undefined) {
if (data[key].thumbnail.source != undefined) {
urli = data[key].thumbnail.source;
break;
}
}
}
return urli;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<div id="wiki"></div>
</body>
</html>

As others have noted, Wikipedia articles don't really have any such thing as a "principal image", so your first problem will be deciding how to choose between the different images used on a given page. Some possible selection criteria might be:
Biggest image in the article.
First image exceeding some specific minimum dimensions, e.g. 60 × 60 pixels.
First image referenced directly in the article's source text, rather than through a template.
For the first two options, you'll want to fetch the rendered HTML code of the page via action=parse and use an HTML parser to find the img tags in the code, like this:
http://en.wikipedia.org/w/api.php?action=parse&page=English_language&prop=text|images
(The reason you can't just get the sizes of the images, as used on the page, directly from the API is that that information isn't actually stored anywhere in the MediaWiki database.)
For the last option, what you want is the source wikitext of the article, available via prop=revisions with rvprop=content:
http://en.wikipedia.org/w/api.php?action=query&titles=English_language&prop=revisions|images&rvprop=content
Note that many images in infoboxes and such are specified as parameters to a template, so just parsing for [[Image:...]] syntax will miss some of them. A better solution is probably to just get the list of all images used on the page via prop=images (which you can do in the same query, as I showed above) and look for their names (with or without Image: / File: prefix) in the wikitext.
Keep in mind the various ways in which MediaWiki automatically normalizes page (and image) names: most notably, underscores are mapped to spaces, consecutive whitespace is collapsed to a single space and the first letter of the name is capitalized. If you decide to go this way, here's some sample PHP code that will convert a list of file names into a regexp that should match any of them in wikitext:
foreach ($names as &$name) {
$name = trim( preg_replace( '/[_\s]+/u', ' ', $name ) );
$name = preg_quote( $name, '/' );
$name = preg_replace( '/^(\\\\?.)/us', '(?i:$1)', $name );
$name = preg_replace( '/\\\\? /u', '[_\s]+', $name );
}
$regexp = '/' . implode( '|', $names ) . '/u';
For example, when given the list:
Anglospeak(800px)Countries.png
Anglospeak.svg
Circle frame.svg
Commons-logo.svg
Flag of Argentina.svg
Flag of Aruba.svg
the generated regexp will be:
/(?i:A)nglospeak\(800px\)Countries\.png|(?i:A)nglospeak\.svg|(?i:C)ircle[_\s]+frame\.svg|(?i:C)ommons\-logo\.svg|(?i:F)lag[_\s]+of[_\s]+Argentina\.svg|(?i:F)lag[_\s]+of[_\s]+Aruba\.svg/u

Important addendum
Bergi's answer, above, seemed super great, but I was bashing my head out because I couldn't get it to work.
I needed to include pilicense=any in my query, because otherwise any copyrighted imagery was ignored.
Here's the query I ultimately got working:
https://en.wikipedia.org/w/api.php?action=query&pilicense=any&format=jsonfm&prop=pageimages&generator=search&gsrsearch=My+incategory:English-language_films+prefix:My&gsrlimit=3
I know it's been awhile, but this is one of the first pages I landed on when I started my days-long search for how to do this, so I wanted to share this specifically on this page, for others like me who might come here.

You can limit your query to the first image in the article with the imlimit parameter:
http://en.wikipedia.org/w/api.php?action=query&titles=English_Language&redirects&prop=images&imlimit=1

Related

How to get xPath nodeValue USD dollar amount

I'm trying to start from the <span> element that has text Value when transacted
Then get its parent <div> and get following sibling which is a <div> and from that <div> get the text of the child <span>.
From what I can tell, the code is correct and should echo $1,034.29.
It echos $0.00 instead.
What am I missing here?
php code:
$a = new DOMXPath($doc);
$dep_val_txt = $a->query("//span[contains(text(), 'Value when transacted')]");
$dep_val_nxt_elem = $a->query("parent::div", $dep_val_txt[0]);
$dep_val_elem = $a->query("following-sibling::*[1]", $dep_val_nxt_elem[0]);
$dep_val = $dep_val_elem->item(0)->childNodes->item(0)->nodeValue;
echo $dep_val;
html code:
<div class="sc-8sty72-0 cyLejs">
<span class="sc-1ryi78w-0 bFGdFC sc-16b9dsl-1 iIOvXh sc-1n72lkw-0 bKaZjn" opacity="1">Value when transacted</span>
</div>
<div class="sc-8sty72-0 cyLejs">
<span class="sc-1ryi78w-0 bFGdFC sc-16b9dsl-1 iIOvXh u3ufsr-0 gXDEBk" opacity="1">$1,034.29</span>
</div>
In case someone else stumbles upon this question in the future, I will summarize the solution which was concluded by conversation with OP in the comments:
The issue here is not with the DOM selectors, as observed by the fact that his output is $0.00 even though he is not formatting the value to appear as a currency. This led me to believe that the website being scraped is in fact using placeholder values which are updated on the client side using Javascript. The reason this cannot be resolved with selectors is because the DOM received by PHP will be the initial render, which does not contain the values we wish to scrape.
So the solution is to examine the website being scraped to determine where and how the values are being fetched before being added to the DOM on the client side. For example, if the website is using an API call to fetch the values, one can simply use the same API to fetch the intended data without having to scrape the HTML DOM at all.
If you follow OPs question literally
start from the <span> element that has text "Value when transacted"
get its parent <div>
get following sibling which is a <div>
get the text of the child <span>
then the xpath expression should be
//span[text()='Value when transacted']/parent::div/following-sibling::div/span
You might find it easier and faster to process using a regex to match the price, here's a quick example in PHP:
<?php
// Your input HTML (as per your example)
$inputHtml = <<<HTML
<div class="sc-8sty72-0 cyLejs">
<span class="sc-1ryi78w-0 bFGdFC sc-16b9dsl-1 iIOvXh sc-1n72lkw-0 bKaZjn" opacity="1">Value when transacted</span>
</div>
<div class="sc-8sty72-0 cyLejs">
<span class="sc-1ryi78w-0 bFGdFC sc-16b9dsl-1 iIOvXh u3ufsr-0 gXDEBk" opacity="1">$1,034.29</span>
</div>
HTML;
$matches = [];
// Look for any div > span element which contains a string starting with $ and then match a number (allowing for a , or . within the price matched).
if (preg_match_all('#<div.*>\s*<span.*?>\$([0-9.,]+)</span>\s*</div>#mis', $inputHtml, $matches)) {
echo 'Price found: ' . $matches[1][0] . PHP_EOL;
}
Console output from this:
Price found: 1,034.29

How to grab specifc data from another website with PHP's fgetcsv and fopen

I'd like to be able to grab data such as list of articles from yahoo finance. At the moment I have a local hosted webpage that searched yahoo finance for stock symbols (E.g Nok), It then returns the opening price, current price, and how far up or down the price has gone.
What I'd like to do is actually grab related links that yahoo has on the page - These links have articles related to the share price...E.g https://au.finance.yahoo.com/q?s=nok&ql=1 Scroll down to headlines, I'd like to grab those links.
At the moment I'm working off a book (PHP Advanced for the world wide web, I know it's old but I found it laying around yesterday and it's quite interesting :) ) In the book it says 'It's important when accessing web pages to know exactly where the data is' - I would think by now there would be a way around this...Maybe the ability to search for links that have a particular keyword in it or something like that!
I'm wondering if theres a special trick I can use to grab particular bits of data on a webpage?? Like crawlers, they are able to grab links that are related to something.
It would be great to know how to do this, then i'd be able to apply it to other subjects in the future.
Ill add my code that I have at the moment. This is purely for practise as I'm learning PHP in my course :)
##getquote.php
<!DOCTYPE html PUBLIC "-//W3// DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>Get Stock Quotes</title>
<link href='css/style.css' type="text/css" rel="stylesheet">
</head>
<h1>Stock Reader</h1>
<body>
<?php
//Read[1] = current price
//read[5] = opening price
//read[4] = down or up whatever percent from opening according to current price
//Step one
//Begin the PHP section my checking if the form has been submitted
if(isset($_POST['submit'])){
//Step two
//Check if a stock symbol was entered.
if(isset($_POST['symbol'])){
//Define the url to be opened
$url = 'http://quote.yahoo.com/d/quotes.csv?s=' . $_POST['symbol'] . '&f=sl1d1t1c1ohgv&e=.csv';
//Open the url, if can't SHUTDOWN script and write msg
$fp = fopen($url, 'r') or die('Cannot Access YAHOO!.');
//This will get the first 30 characters from the file located in $fp
$read = fgetcsv ($fp, 30);
//Close the file processsing.
fclose($fp);
include("php/displayDetails.php");
}
else{
echo "<div style='color:red'>Please enter a SYMBOL before submitting the form</div>";
}
}
?>
<form action='getquote.php' method='post'>
<p>Symbol: </p><input type='text' name='symbol'>
<br />
<input type="submit" value='Fetch Quote' name="submit">
</form>
<br />
<br />
##displayDetails.php
<div class='display-contents'>
<?php
echo "<div>Todays date: " . $read[2] . "</div>";
//Current price
echo "<div>The current value for " . $_POST["symbol"] . " is <strong>$ " . $read[1] . "</strong></div>";
//Opening Price
echo "<div>The opening value for " . $_POST["symbol"] . " is <strong>$ " . $read[5] . "</strong></div>";
if($read[1] < $read[5])
{
//Down or Up depending on opening.
echo "<div>" .strtoupper($_POST['symbol']) ."<span style='color:red'> <em>IS DOWN</em> </span><strong>$" . $read[4] . "</strong></div>";
}
else{
echo "<div>" . strtoupper($_POST['symbol']) ."<span style='color:green'> <em>IS UP</em> </span><strong>$" . $read[4] . "</strong></div>";
}
added code to displayDetails.php
function getLinks(){
$siteContent = file_get_contents($url);
$div = explode('class="yfi_headlines">',$siteContent);
// every thing inside is a content you want
$innerContent = explode('<div class="ft">',$div)[0]; //now you have inner content of your div;
$list = explode("<ul>",$innerConent)[1];
$list = explode("</ul>",$list)[0];
echo $list;
}
?>
</div>
I just the same code in - I didn't really know what I should do with it?!
Idk for fgetcsv but with file_get_contents you can grab whole content of a page into a string variable.
Then you can search for links in string (do not use regex for html content search: Link regex)
I briefly looked at yahoo's source code so you can do:
-yfi_headlines is a div class witch wrappes desired links
$siteContent = file_get_contents($url);
$div = explode('class="yfi_headlines">',$siteContent)[1]; // every thing inside is a content you want
-last class inside searched div is: ft
$innerContent = explode('<div class="ft">',$div)[0]; //now you have inner content of your div;
repeat for getting <ul> inner content
$list = explode("<ul>",$innerConent)[1];
$list = explode("</ul>",$list)[0];
now you have a list of links in format: <li>text</li>
There are more efficient ways to parse web page like using DOMDocument:
Example
For getting content of a page you can also look at this answer
https://stackoverflow.com/a/15706743/2656311
[ADITIONALY] IF it is a large website: at the beggining of a function do: ini_set("memory_limit","1024M"); so you can store more data to your memory!

Need to add a search to static HTML site

Basically I've got an old static html site ( http://www.brownwatson.co.uk/brochure/page1.html ) I need to add a search box to it to search a folder called /brochure within that folder is html documents and images etc I need the search to find ISBN numbers, Book Reference Numbers, Titles etc.. There's no database the hosting provider has got php I was trying to create something like this:
<div id="contentsearch">
<form id="searchForm" name="searchForm" method="post" action="search.php">
<input name="search" type="text" value="search" maxlength="200" />
<input name="submit" type="submit" value="Search" />
</form>
<?php
$dir = "/brochure/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($file == $_POST['search']){
echo(''. $file .''."\n");
}
}
closedir($dh);
}
}
?>
</div>
I know, I know this is pretty bad and doesn't work any ideas? I haven't created anything like this in years, and have pretty much just taken bits of code and stuck it together!
There are quite a few solutions available for this. In no particular order:
Free or Open Source
Google Custom Search Engine
Tapir - hosted service that indexes pages on your RSS feed.
Tipue - self hosted javaScript plugin, well documented, includes options for pinned search results.
lunr.js - javaScript library.
phinde - self hosted php and elasticsearch based search engine
See also http://indieweb.org/search#Software
Subscription (aka paid) Services:
Google Site Search
Swiftype - offers a free plan for personal sites/blogs.
Algolia
Amazon Cloud Search
A very, very lazy option (to avoid setting up a Google Custom Search Engine) is to make a form that points at Google with a hidden query element that limits the search to your own site:
<div id="contentsearch">
<form id="searchForm" name="searchForm" action="http://google.com/search">
<input name="q" type="text" value="search" maxlength="200" />
<input name="q" type="hidden" value="site:mysite.com"/>
<input name="submit" type="submit" value="Search" />
</form>
</div>
Aside from the laziness, this method gives you a bit more control over the appearance of the search form, compared to a CSE.
I was searching for solution for searching for my blog created using Jekyll but didn't found good one, also Custom Google Search was giving me ads and results from subdomains, so it was not good. So I've created my own solution for this. I've written an article about how to create search for static site like Jekyll it's in Polish and translated using google translate.
Probably will create better manual translation or rewrite on my English blog soon.
The solution is python script that create SQLite database from HTML files and small PHP script that show search results. But it will require that your static site hosting also support PHP.
Just in case the article go down, here is the code, it's created just for my blog (my html and file structure) so it need to be tweaked to work with your blog.
Python script:
import os, sys, re, sqlite3
from bs4 import BeautifulSoup
def get_data(html):
"""return dictionary with title url and content of the blog post"""
tree = BeautifulSoup(html, 'html5lib')
body = tree.body
if body is None:
return None
for tag in body.select('script'):
tag.decompose()
for tag in body.select('style'):
tag.decompose()
for tag in body.select('figure'): # ignore code snippets
tag.decompose()
text = tree.findAll("div", {"class": "body"})
if len(text) > 0:
text = text[0].get_text(separator='\n')
else:
text = None
title = tree.findAll("h2", {"itemprop" : "title"}) # my h2 havee this attr
url = tree.findAll("link", {"rel": "canonical"}) # get url
if len(title) > 0:
title = title[0].get_text()
else:
title = None
if len(url) > 0:
url = url[0]['href']
else:
url = None
result = {
"title": title,
"url": url,
"text": text
}
return result
if __name__ == '__main__':
if len(sys.argv) == 2:
db_file = 'index.db'
# usunięcie starego pliku
if os.path.exists(db_file):
os.remove(db_file)
conn = sqlite3.connect(db_file)
c = conn.cursor()
c.execute('CREATE TABLE page(title text, url text, content text)')
for root, dirs, files in os.walk(sys.argv[1]):
for name in files:
# my files are in 20.* directories (eg. 2018) [/\\] is for windows and unix
if name.endswith(".html") and re.search(r"[/\\]20[0-9]{2}", root):
fname = os.path.join(root, name)
f = open(fname, "r")
data = get_data(f.read())
f.close()
if data is not None:
data = (data['title'], data['url'], data['text']
c.execute('INSERT INTO page VALUES(?, ?, ?)', data))
print "indexed %s" % data['url']
sys.stdout.flush()
conn.commit()
conn.close()
and PHP search script:
function mark($query, $str) {
return preg_replace("%(" . $query . ")%i", '<mark>$1</mark>', $str);
}
if (isset($_GET['q'])) {
$db = new PDO('sqlite:index.db');
$stmt = $db->prepare('SELECT * FROM page WHERE content LIKE :var OR title LIKE :var');
$wildcarded = '%'. $_GET['q'] .'%';
$stmt->bindParam(':var', $wildcarded);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$query = str_replace("%", "\\%", preg_quote($_GET['q']));
$re = "%(?>\S+\s*){0,10}(" . $query . ")\s*(?>\S+\s*){0,10}%i";
if (count($data) == 0) {
echo "<p>Brak wyników</p>";
} else {
foreach ($data as $row) {
if (preg_match($re, $row['content'], $match)) {
echo '<h3>' . mark($query, $row['title']) . '</h2>';
$text = trim($match[0], " \t\n\r\0\x0B,.{}()-");
echo '<p>' . mark($query, $text) . '</p>';
}
}
}
}
In my code an in article I've wrapped this PHP script in the same layout as other pages by adding front matter to PHP file.
If you can't use PHP on your hosting you can try to use sql.js which is SQLite compiled to JS with Emscripten.
If your site is well index by Google a quick and ready solution is use Google CSE.
Other than that for a static website with hard coded html pages and directory containing images; yes it is possible to create search mechanism. But trust me it is more hectic and resource consuming then creating a dynamic website.
Using PHP to search in directories and within files will be very inefficient. Instead of providing complicated PHP workarounds I would suggest go for a dynamic CMS driven website.

<enclosure> not working rss and php

I'm working on a rss feed for a website I made. It takes input from my home made news function on the site, which is stored in a MySQL database.
Now I can get the text nicely enough, but when I try to use <enclosure> to put in an image, nothing shows up.
The code i use to insert the code is as follows:
if($rows['image'] != 0) {
$image = mysql_fetch_array(mysql_query("SELECT * FROM dafl_news_imagedb WHERE id = '".$rows['image']."' LIMIT 1"));
$imageUrl = "http://dafl.dk/content/news/pics/".$image['filename'];
$imageType = substr($imageUrl, strlen($imageUrl) - 3, 3);
$enclosedImage = '
<enclosure url="'.$imageUrl.'" length="0" type="image/'.$imageType.'" />
';
echo $enclosedImage;
}
and in the source code of the rss:
<enclosure url="http://dafl.dk/content/news/pics/13.png" length="0" type="image/png" />
The link to the rss is:
http://dafl.dk/rss/?language=en
(The picture is only included when an image is present for the newspost. Is this a problem - that not all items have an enclosure ?
Try this link to see if the enclosure tag works in the target browser.
http://www.w3schools.com/rss/tryrss.asp?filename=rss_ex_enclosure
References:
http://www.w3schools.com/rss/rss_tag_enclosure.asp

Echoing out JavaScript with nested quotes from a PHP script onto an HTML page?

I've been trying for about two hours to get the following code stored in a PHP string and then echoed out as JavaScript on a webpage:
<div id="reply-box" style="display: block; width:100%;float:right;">
<script type="text/javascript" src="http://example.com/public/js/3rd_party/ckeditor/ckeditor.js"></script>
<script type="text/javascript">
/* Dynamic items */
CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]","switch_option":"0","menu_option_text":"Enter the description for this acronym (EG: Laugh Out Loud)","menu_content_text":"Enter the acronym (EG: lol)","single_tag":"0","optional_option":"0","image":""},"ads1":{"id":"46","title":"ads1","desc":"","tag":"ads1","useoption":"0","example":"","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"1","optional_option":"0","image":""},"background":{"id":"27","title":"Background-color","desc":"Adds a background color behind the text","tag":"background","useoption":"1","example":"[background=red]Red background behind this text[/background]","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"entry":{"id":"35","title":"Blog Entry Link","desc":"This tag provides an easy way to link to a blog entry.","tag":"entry","useoption":"1","example":"[entry=100]Click me![/entry]","switch_option":"0","menu_option_text":"Entry ID","menu_content_text":"Text to display","single_tag":"0","optional_option":"0","image":""},"blog":{"id":"34","title":"Blog Link","desc":"This tag provides an easy way to link to a blog.","tag":"blog","useoption":"1","example":"[blog=100]Click me![/blog]","switch_option":"0","menu_option_text":"Blog ID","menu_content_text":"Text to display","single_tag":"0","optional_option":"0","image":""},"code":{"id":"13","title":"Code","desc":"Allows you to enter general code","tag":"code","useoption":"0","example":"[code]$text = 'Some long code here';[/code]","switch_option":"0","menu_option_text":"","menu_content_text":"Code","single_tag":"0","optional_option":"0","image":""},"extract":{"id":"33","title":"Extract Blog Entry","desc":"This will allow users to define an extract for an entry. Only this piece of the entry will be displayed on the main blog page and will show up in the RSS feed.","tag":"extract","useoption":"0","example":"[extract]This is an example![/extract]","switch_option":"0","menu_option_text":"","menu_content_text":"Blog entry extract","single_tag":"0","optional_option":"0","image":""},"hr":{"id":"12","title":"Horizontal Rule","desc":"Adds a horizontal rule to separate text","tag":"hr","useoption":"0","example":"[hr]","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"1","optional_option":"0","image":""},"html":{"id":"15","title":"HTML Code","desc":"Allows you to enter formatted/syntax-highlighted HTML code","tag":"html","useoption":"0","example":"[html]<div class='outer'>\n <p>Hello World</p>\n </div>[/html]","switch_option":"0","menu_option_text":"","menu_content_text":"HTML Code","single_tag":"0","optional_option":"0","image":""},"imgr":{"id":"39","title":"Image","desc":"Displays linked images, floating to the right","tag":"imgr","useoption":"0","example":"[imgr]http://www.google.com/intl/en_ALL/images/logo.gif[/imgr]","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"jump":{"id":"45","title":"jump","desc":"","tag":"jump","useoption":"0","example":"","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"media":{"id":"32","title":"Media","desc":"Allows a user to post media content from certain common media sites","tag":"media","useoption":"1","example":"[media]http://www.youtube.com/watch?v=YqqLx-2vUr0[/media]","switch_option":"0","menu_option_text":"Dimensions (Flash Only)","menu_content_text":"Media URL","single_tag":"0","optional_option":"1","image":""},"member":{"id":"31","title":"Member","desc":"Given a member name, a link is automatically generated to the member's profile","tag":"member","useoption":"1","example":"[member=admin] runs this site.","switch_option":"0","menu_option_text":"Member Name","menu_content_text":"","single_tag":"1","optional_option":"0","image":""},"page":{"id":"38","title":"Multi-Page Articles","desc":"This tag can be used to create multi-page articles. Page links are automatically added based on the number of times this tag is used, and the content is hidden until you reach the specified \"page\".","tag":"page","useoption":"0","example":"Content 1\n[page]\nContent 2\n[page]\nContent 3","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"1","optional_option":"0","image":""},"overline":{"id":"42","title":"Overlined Text","desc":"Makes the text overlined","tag":"overline","useoption":"0","example":"[overline]This text is underlined[/overline]","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"php":{"id":"14","title":"PHP Code","desc":"Allows you to enter PHP code into a formatted/highlighted syntax box","tag":"php","useoption":"0","example":"[php]$variable = true;\n\nprint_r($variable);[/php]","switch_option":"0","menu_option_text":"","menu_content_text":"PHP Code","single_tag":"0","optional_option":"0","image":""},"post":{"id":"6","title":"Post Link","desc":"This tag provides an easy way to link to a post.","tag":"post","useoption":"1","example":"[post=1]Click me![/post]","switch_option":"0","menu_option_text":"Enter the Post ID","menu_content_text":"Enter the title for this link","single_tag":"0","optional_option":"0","image":""},"pre":{"id":"43","title":"pre","desc":"","tag":"pre","useoption":"0","example":"","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"spoiler":{"id":"7","title":"Spoiler","desc":"Spoiler tag","tag":"spoiler","useoption":"0","example":"[spoiler]Some hidden text[/spoiler]","switch_option":"0","menu_option_text":"","menu_content_text":"Enter the text to be masked","single_tag":"0","optional_option":"0","image":""},"sql":{"id":"16","title":"SQL Code","desc":"Allows you to enter formatted/syntax-highlighted SQL code","tag":"sql","useoption":"0","example":"[sql]SELECT p.*, t.* FROM posts p LEFT JOIN topics t ON t.tid=p.topic_id WHERE t.tid=7[/sql]","switch_option":"0","menu_option_text":"","menu_content_text":"SQL Commands","single_tag":"0","optional_option":"0","image":""},"tab":{"id":"48","title":"tab","desc":"adds a tab (twelve spaces)","tag":"tab","useoption":"0","example":"[tab]","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"1","optional_option":"0","image":""},"tex":{"id":"41","title":"tex","desc":"LaTeX","tag":"tex","useoption":"0","example":"","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"topic":{"id":"5","title":"Topic Link","desc":"This tag provides an easy way to link to a topic","tag":"topic","useoption":"1","example":"[topic=1]Click me![/topic]","switch_option":"0","menu_option_text":"Enter the topic ID","menu_content_text":"Enter the title for this link","single_tag":"0","optional_option":"0","image":""},"twitter":{"id":"36","title":"Twitter","desc":"A tag to link to a user's twitter account","tag":"twitter","useoption":"0","example":"[twitter]userName[/twitter]","switch_option":"0","menu_option_text":"","menu_content_text":"Twitter Username","single_tag":"0","optional_option":"0","image":"twitter.png"},"xml":{"id":"17","title":"XML Code","desc":"Allows you to enter formatted/syntax-highlighted XML code","tag":"xml","useoption":"0","example":"[xml]<outer>\n <inner>\n <tag param='1'>Test</tag>\n </inner>\n</outer>[/xml]","switch_option":"0","menu_option_text":"","menu_content_text":"XML Code","single_tag":"0","optional_option":"0","image":""}};
CKEDITOR.config.IPS_BBCODE_IMG_URL = "http://example.com/public/style_extra/bbcode_icons";
CKEDITOR.config.IPS_BBCODE_BUTTONS = [];
/* Has to go before config load */
var IPS_smiley_path = "http://example.com/public/style_emoticons/default/";
var IPS_smiles = {"total":20,"count":20,"emoticons":[{"src":"mellow.png","text":":mellow:"},{"src":"dry.png","text":"<_<"},{"src":"smile.png","text":":)"},{"src":"wub.png","text":":wub:"},{"src":"angry.png","text":":angry:"},{"src":"sad.png","text":":("},{"src":"unsure.png","text":":unsure:"},{"src":"wacko.png","text":":wacko:"},{"src":"blink.png","text":":blink:"},{"src":"sleep.png","text":"-_-"},{"src":"rolleyes.gif","text":":rolleyes:"},{"src":"huh.png","text":":huh:"},{"src":"happy.png","text":"^_^"},{"src":"ohmy.png","text":":o"},{"src":"wink.png","text":";)"},{"src":"tongue.png","text":":P"},{"src":"biggrin.png","text":":D"},{"src":"laugh.png","text":":lol:"},{"src":"cool.png","text":"B)"},{"src":"ph34r.png","text":":ph34r:"}]};
var IPS_remove_plugins = [];
var IPS_hide_contextMenu = 0;
var IPS_rclick_contextMenu = 0;
/* Has to go after */
/* Load our configuration */
CKEDITOR.config.customConfig = 'http://example.com/public/js/3rd_party/ckeditor/ips_config.js';
</script>
<input type='hidden' name='isRte' id='isRte_editor_4fe2476d708e8' value='1' />
<textarea id="ipb_editor" name="Post" class='ipsEditor_textarea input_text'></textarea>
<p class='desc ipsPad' style='display: none' id='editor_html_message_editor_4fe2476d708e8'></p>
<script type="text/javascript">
ipb.textEditor.initialize('editor_4fe2476d708e8', { type: 'full',
height: 200,
minimize: 0,
bypassCKEditor: 0,
delayInit: 0,
isHtml: 0,
isRte: 1,
isTypingCallBack: '',
ips_AutoSaveKey: '',
ips_AutoSaveData: [] } );
</script>
</div>
I've tried escaping quotes using several different JavaScript and PHP methods, but no matter what I try I can't get it echoed out without either breaking the page or the editor not working.
Does anyone know of a way to get this code stored in a string in a manner that can be then echoed out onto the page as working JavaScript?
Try:
<?php ob_start(); ?>
<div id="reply-box" style="display: block; width:100%;float:right;">
<script type="text/javascript" src="http://example.com/public/js/3rd_party/ckeditor/ckeditor.js"></script>
<script type="text/javascript">
.... your HTML/Javascript
</script>
</div>
<?php
$string = ob_get_contents();
ob_end_clean();
?>
I don't have your javascript libs but it appears to show up fine when I echo out $string. PHP is basically copying all of the display content to a buffer and instead of rendering the page, we copy it to a variable.
$variable = <<<END
xxx
xxx
xxx
END;
echo $variable;
Make sure you have END; on it's own line WITHOUT whitespace before it.
Hope have helped!

Categories