I'm using a php to code to fetch images and data from the other urls
but need to convert images to base64 string..!!
the code is
<?php
function getMetaTitle($content){
$pattern = "|<[\s]*title[\s]*>([^<]+)<[\s]*/[\s]*title[\s]*>|Ui";
if(preg_match($pattern, $content, $match))
return $match[1];
else
return false;
}
function fetch_record($path)
{
$file = fopen($path, "r");
if (!$file)
{
exit("Problem occured");
}
$data = '';
while (!feof($file))
{
$data .= fgets($file, 1024);
}
return $data;
}
$url = $_POST['url'];
$data = array();
// get url title
$content = #file_get_contents($url);
$data['title'] = getMetaTitle($content);
// get url description from meta tag
$tags = #get_meta_tags($url);
$data['description'] = $tags['description'];
$string = fetch_record($url);
// fetch images
$image_regex = '/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex, $content, $img, PREG_PATTERN_ORDER);
$images_array = $img[1];
$k=1;
for ($i=0;$i<=sizeof($images_array);$i++)
{
if(#$images_array[$i])
{
if(#getimagesize(#$images_array[$i]))
{
list($width, $height, $type, $attr) = getimagesize(#$images_array[$i]);
if($width > 50 && $height > 50 ){
$data['images'] = "<img src='".#$images_array[$i]."' id='".$k."' width='100%'>";
$k++;
}
}
}
}
$data['form'] = '<input type="hidden" name="images" value="'.$data['images'].'"/>
<input type="hidden" name="title" value="'.$data['title'].'"/>
<input type="hidden" name="description" value="'.$data['description'].'"/>';
$dom = new domDocument;
#$dom->loadHTML($content);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach($images as $img)
{
$url = $img->getAttribute('src');
$alt = $img->getAttribute('alt');
$pos = strpos($url, 'http://');
if ($pos === false) {
// $data['images'] = '<img src="'.$_POST['url'].''.$url.'" title="'.$alt.'"/>';
} else {
// $data['images'] = '<img src="'.$url.'" title="'.$alt.'"/>';
}
}
echo json_encode($data);
?>
This code use images in there Standard extension on this line
$data['images'] = "<img src='".#$images_array[$i]."' id='".$k."' width='100%'>";
I want to convert them to base64 and them use
Once you have the url for the image you just need to grab it with curl and call base64_encode.
chunk_split just makes it perdy.
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true );
$ret_val = curl_exec($curl);
// TODO: error checking!!!
$b64_image_data = chunk_split(base64_encode($ret_val));
curl_close($curl);
Another option is to get PHP to filter the image's binary data into a Base64 encoded value with a stream conversion filter (docs).
$img_url = 'http://www.php.net/images/php.gif';
$b64_url = 'php://filter/read=convert.base64-encode/resource='.$img_url;
$b64_img = file_get_contents($b64_url);
echo $b64_img;
Related
I have this issue on one of servers, Up until last week, the feed it was pulling the content from was working fine. Now suddenly since last few days, when I made the change to extract category field from database since then it is not extracting the image from the feed but is able to extract all of other content. (This server was set up by previous developer).
I keep getting this error:
going to get file 2020-07-23T15:41:05
going to put /var/www/SpanishMix/
!! problem getting remote file ( 2020-07-23T15:41:05 ) in checkNGet ** trying replace , digiv/2105318.jpg
This is the code in php file:
<?php
set_time_limit(90);
ini_set('memory_limit', '128M');
$xurl = 'feedlink.com/feed/getXML.php';
$locs = 'server ip';
$locvid = '/var/www/SpanishMix/';
function decrypto($inStr)
{
$key = '';
$encrypted = $inStr;
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
return $decrypted;
}
function dis($v)
{
echo "<pre>\n";
print_r($v);
echo "\n</pre>\n<hr>\n";
}
// --------------------- grab XML
$c = file_get_contents($xurl);
if (strlen($c) < 100) {
exit('couldnt get data from CMS');
}
// --------------------- parse into usable array of objects
$sa = array();
$ta1 = explode('_ENDI_', $c);
foreach ($ta1 as $i) {
$ta2 = explode('_ENDF_', $i);
if ((strlen($ta2[0]) > 4) && (strlen($i) > 200)) {
$to = new stdClass();
$to->uid = $ta2[0];
$to->vurl = "";
$to->body = $ta2[1];
$to->people = trim($ta2[2]);
$to->headline = trim($ta2[3]);
$to->category = trim($ta2[4]);
$to->abstract = trim($ta2[5]);
$to->pubdate = trim($ta2[7]);
$to->storyid = trim($ta2[6]);
$to->iurl = trim($ta2[8]);
$tmpia = explode('.com/', $to->iurl);
$to->cpi = $tmpia[1];
$to->iloc = 'http://' . $locs . '/SpanishMix/' . $tmpia[1];
// code for durability date
$tmpda = explode('-', $to->pubdate);
$oldy = $tmpda[0];
$newy = $oldy + 1;
$newys = str_replace($oldy, $newy, $to->pubdate);
$to->durdate = $newys;
$to->gotv = 0;
$to->fs = 0;
if ($to->uid > 10000) {
$sa[$to->uid] = $to;
}
}
}
dis($sa);
// --------------------- scan vids dir, parse into array including filesize
$va = array();
$dir = $locvid . "*.jpg";
foreach (glob($dir) as $file) {
$tv = new stdClass();
$tv->fn = $file;
$tv->s = filesize($file);
array_push($va, $tv);
}
dis($va);
// --------------------- check through stories array structure marking those already with video
$vtg = '';
$itg = '';
$uidtg = '';
// loop through each story
foreach ($sa as $s) {
$found = 0;
foreach ($va as $v) {
// hack out matchable filename from video and story arrays
$tfn = '/var/www/SpanishMix/' . $s->cpi;
if ($tfn == $v->fn) {
$found = 1;
}
}
// if outer looop variable says no video found for this story, make this storey's video URL next to get
if (!$found) {
echo "<br>setting itg to $s->iurl<br>\n";
$itg = $s->iurl;
$uidtg = $s->uid;
}
}
echo "<hr><h1> getting video part</h1><br><br>";
// --------------------- elect first story entry with no file
if ($itg) {
// split img url to take
$ifa = explode('.com/', $itg);
$itg = $itg;
$outfile = '/var/www/SpanishMix/' . $ifa[1];
echo "\n<br><b>going to get file $itg<br>going to put $outfile</b><br>\n";
$remoteFile = file_get_contents($itg);
if (!$remoteFile) {
echo "!! problem getting remote file ( $itg ) in checkNGet\n\n";
} else {
$res = file_put_contents($outfile, $remoteFile);
if ($res) {
echo "put remote image file ( $outfile ) success !\n\n\n";
// NOW COPY LOCAL FILE TO FUNNY FILENAME
$cpifn = '/var/www/SpanishMix/digiv/' . $uidtg . '.jpg';
echo "* about to copy $outfile to $cpifn\n\n";
copy($outfile, $cpifn);
} else {
echo "put remote image file ( $outfile ) fail :( \n\n\n<br><br>";
}
}
}
$tt = '';
$tm = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<videonews>
<news>
<name>BBCC**storyid**</name>
<title>**headline**</title>
<subtitle>**abstract**</subtitle>
<text>**body**</text>
<keywords>**people**</keywords>
<date>**pubdate**</date>
<durability>**durdate**</durability>
<category>**category**</category>
<subcategory>Famosos</subcategory>
<image>
<file format="image">**iloc**</file>
</image>
</news>
</videonews>
';
$tb = '';
$out = $tt;
foreach ($sa as $s) {
if ($s->uid == $uidtg) {
$tfn = "$locs/SpanishMix/" . $tfna[3];
$tmpt = str_replace('**body**', $s->body, $tm);
//$tmpt = str_replace('**vidfs**', $s->fs, $tmpt);
$tmpt = str_replace('**headline**', $s->headline, $tmpt);
$tmpt = str_replace('**people**', $s->people, $tmpt);
$tmpt = str_replace('**abstract**', $s->abstract, $tmpt);
$tmpt = str_replace('**storyid**', $s->storyid, $tmpt);
$tmpt = str_replace('**category**', $s->category, $tmpt);
$tmpt = str_replace('**pubdate**', $s->pubdate, $tmpt);
$tmpt = str_replace('**durdate**', $s->durdate, $tmpt);
$tmpt = str_replace('**iloc**', $s->iloc, $tmpt);
$copyA2 = explode('SpanishMix/', $s->iloc);
$copyImageFN = $copyA2[1];
$copyNewImageFN = 'digiv/' . $uidtg . '.jpg';
echo "\n ** trying replace $copyImageFN, $copyNewImageFN\n";
$tmpt = str_replace($copyImageFN, $copyNewImageFN, $tmpt);
$out .= "$tmpt\n\n";
}
}
$out .= $tb;
if ($uidtg) {
echo "</pre><TEXTAREA cols='120' rows='80'>$out</TEXTAREA>\n";
echo "<hr>";
$ox = '/var/www/SpanishMix/digiv/' . $uidtg . '.xml';
$written = file_put_contents($ox, $out);
echo "\nALSO putting : xml to $ox [", $written, "]<br>\n";
} else {
echo "\n NO UIDTG [", $uidtg, "] ! \n not putting any files";
}
I would really appreciate some help on this.
I am parsing a xml and but there is a tag which contain image and text both and i want to seprate both image and text in diffrent columns of table in my design layout but i dont know how to do it. please help me. my php file is :
<?php
$RSS_Content = array();
function RSS_Tags($item, $type)
{
$y = array();
$tnl = $item->getElementsByTagName("title");
$tnl = $tnl->item(0);
$title = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("link");
$tnl = $tnl->item(0);
$link = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("description");
$tnl = $tnl->item(0);
$img = $tnl->firstChild->textContent;
$y["title"] = $title;
$y["link"] = $link;
$y["description"] = $img;
$y["type"] = $type;
return $y;
}
function RSS_Channel($channel)
{
global $RSS_Content;
$items = $channel->getElementsByTagName("item");
// Processing channel
$y = RSS_Tags($channel, 0); // get description of channel, type 0
array_push($RSS_Content, $y);
// Processing articles
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
function RSS_Retrieve($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
RSS_Channel($channel);
}
}
function RSS_RetrieveLinks($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
$items = $channel->getElementsByTagName("item");
foreach($items as $item)
{
$y = RSS_Tags($item, 1);
array_push($RSS_Content, $y);
}
}
}
function RSS_Links($url, $size = 15)
{
global $RSS_Content;
$page = "<ul>";
RSS_RetrieveLinks($url);
if($size > 0)
$recents = array_slice($RSS_Content, 0, $size + 1);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0) continue;
$title = $article["title"];
$link = $article["link"];
$img = $article["description"];
$page .= "$title\n";
}
$page .="</ul>\n";
return $page;
}
function RSS_Display($url, $click, $size = 8, $site = 0, $withdate = 0)
{
global $RSS_Content;
$opened = false;
$page = "";
$site = (intval($site) == 0) ? 1 : 0;
RSS_Retrieve($url);
if($size > 0)
$recents = array_slice($RSS_Content, $site, $size + 1 - $site);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0)
{
if($opened == true)
{
$page .="</ul>\n";
$opened = false;
}
$page .="<b>";
}
else
{
if($opened == false)
{
$page .= "<table width='369' border='0'>
<tr>";
$opened = true;
}
}
$title = $article["title"];
$link = $article["link"];
$img = $article["description"];
$page .= "<td width='125' align='center' valign='middle'>
<div align='center'>$img</div></td>
<td width='228' align='left' valign='middle'><div align='left'><a
href=\"$click\" target='_top'>$title</a></div></td>";
if($withdate)
{
$date = $article["date"];
$page .=' <span class="rssdate">'.$date.'</span>';
}
if($type==0)
{
$page .="<br />";
}
}
if($opened == true)
{
$page .="</tr>
</table>";
}
return $page."\n";
}
?>
To separate the image and description you need to parse the HTML that is stored inside the description element again as XML. Luckily it is valid XML inside that element, therefore you can do this straight forward with SimpleXML, the following code-example take the URL and converts each item *description* into the text only and extracts the src attribute of the image to store it as the image element:
<item>
<title>Fake encounter: BJP backs Kataria, says CBI targeting Modi</title>
<link>http://ibnlive.in.com/news/fake-encounter-bjp-backs-kataria-says-cbi-targeting-modi/391802-37-64.html</link>
<description>The BJP lashed out at the CBI and questioned its 'shoddy investigation' into the Sohrabuddin fake encounter case.</description>
<pubDate>Wed, 15 May 2013 13:48:56 +0530</pubDate>
<guid>http://ibnlive.in.com/news/fake-encounter-bjp-backs-kataria-says-cbi-targeting-modi/391802-37-64.html</guid>
<image>http://static.ibnlive.in.com/ibnlive/pix/sitepix/05_2013/bjplive_kataria3.jpg</image>
</item>
The code-example is:
$url = 'http://ibnlive.in.com/ibnrss/top.xml';
$feed = simplexml_load_file($url);
$items = $feed->xpath('(//channel/item)');
foreach ($items as $item) {
list($description, $image) =
simplexml_load_string("<r>$item->description</r>")
->xpath('(/r|/r//#src)');
$item->description = (string)$description;
$item->image = (string)$image;
}
You can then import the SimpleXML into a DOMElement with dom_import_simplexml() however honestly, I just would wrap that little HTML creation as well into a foreach of SimpleXML because you can make use of LimitIterator for the paging as well as you could with DOMDocument and the data you access is actually easily at hand with SimpleXML, it's just easy to pass along the XML elements as SimpleXMLElements instead of parsing into an array first and then processing the array. That's moot.
My goal is to create pages with information needed about the movie and with links that redirect to a video host where you will watch it. I found an IMDB php plugin and I am trying to insert in jquery mobile so mobile users will easily find the movies and stream them on their iDevices or any device that supports MP4 formats. Something close to http://freeflix.technoinsidr.com/watch.php?m=tt1190080
I've made this http://ivids.tk/test.php?m=tt0068646 How can I remove TITLE, YEAR (everything that's in BOLD) and put TITLE with the YEAR on the same line if its possible touse jquery mobile as the design? Is it even possible?
<?php
class Imdb
{
function getMovieInfo($title)
{
$imdbId = $this->getIMDbIdFromGoogle(trim($title));
if($imdbId === NULL){
$arr = array();
$arr['error'] = "No Title found in Search Results!";
return $arr;
}
return $this->getMovieInfoById($imdbId);
}
function getMovieInfoById($imdbId)
{
$arr = array();
$imdbUrl = "http://www.imdb.com/title/" . trim($imdbId) . "/";
$html = $this->geturl($imdbUrl);
if(stripos($html, "<meta name=\"application-name\" content=\"IMDb\" />") !== false){
$arr = $this->scrapMovieInfo($html);
$arr['imdb_url'] = $imdbUrl;
} else {
$arr['error'] = "No Title found on IMDb!";
}
return $arr;
}
function getIMDbIdFromGoogle($title){
$url = "http://www.google.com/search?q=imdb+" . rawurlencode($title);
$html = $this->geturl($url);
$ids = $this->match_all('/<a href="http:\/\/www.imdb.com\/title\/(tt\d+).*?".*?>.*?<\/a>/ms', $html, 1);
if (!isset($ids[0])) //if Google fails
return $this->getIMDbIdFromBing($title); //search using Bing
else
return $ids[0]; //return first IMDb result
}
function getIMDbIdFromBing($title){
$url = "http://www.bing.com/search?q=imdb+" . rawurlencode($title);
$html = $this->geturl($url);
$ids = $this->match_all('/<a href="http:\/\/www.imdb.com\/title\/(tt\d+).*?".*?>.*?<\/a>/ms', $html, 1);
if (!isset($ids[0]))
return NULL;
else
return $ids[0]; //return first IMDb result
}
// Scan movie meta data from IMDb page
function scrapMovieInfo($html)
{
$arr = array();
$arr['title'] = trim($this->match('/<title>(IMDb \- )*(.*?) \(.*?<\/title>/ms', $html, 2));
$arr['year'] = trim($this->match('/<title>.*?\(.*?(\d{4}).*?\).*?<\/title>/ms', $html, 1));
$arr['rating'] = $this->match('/ratingValue">(\d.\d)</ms', $html, 1);
$arr['genres'] = array();
foreach($this->match_all('/<a.*?>(.*?)<\/a>/ms', $this->match('/Genre.?:(.*?)(<\/div>|See more)/ms', $html, 1), 1) as $m)
array_push($arr['genres'], $m);
//Get extra inforation on Release Dates and AKA Titles
if($arr['title_id'] != ""){
$releaseinfoHtml = $this->geturl("http://www.imdb.com/title/" . $arr['title_id'] . "/releaseinfo");
$arr['also_known_as'] = $this->getAkaTitles($releaseinfoHtml, $usa_title);
$arr['usa_title'] = $usa_title;
$arr['release_date'] = $this->match('/Release Date:<\/h4>.*?([0-9][0-9]? (January|February|March|April|May|June|July|August|September|October|November|December) (19|20)[0-9][0-9]).*?(\(|<span)/ms', $html, 1);
$arr['release_dates'] = $this->getReleaseDates($releaseinfoHtml);
}
$arr['plot'] = trim(strip_tags($this->match('/<p itemprop="description">(.*?)(<\/p>|<a)/ms', $html, 1)));
$arr['poster'] = $this->match('/img_primary">.*?<img src="(.*?)".*?<\/td>/ms', $html, 1);
$arr['poster_small'] = "";
if ($arr['poster'] != '' && strrpos($arr['poster'], "nopicture") === false && strrpos($arr['poster'], "ad.doubleclick") === false) { //Get large and small posters
$arr['poster_small'] = preg_replace('/_V1\..*?.jpg/ms', "_V1._SY150.jpg", $arr['poster']);
} else {
$arr['poster'] = "";
}
$arr['runtime'] = trim($this->match('/Runtime:<\/h4>.*?(\d+) min.*?<\/div>/ms', $html, 1));
if($arr['runtime'] == '') $arr['runtime'] = trim($this->match('/infobar.*?(\d+) min.*?<\/div>/ms', $html, 1));
$arr['storyline'] = trim(strip_tags($this->match('/Storyline<\/h2>(.*?)(<em|<\/p>|<span)/ms', $html, 1)));
$arr['language'] = array();
foreach($this->match_all('/<a.*?>(.*?)<\/a>/ms', $this->match('/Language.?:(.*?)(<\/div>|>.?and )/ms', $html, 1), 1) as $m)
array_push($arr['language'], trim($m));
$arr['country'] = array();
foreach($this->match_all('/<a.*?>(.*?)<\/a>/ms', $this->match('/Country:(.*?)(<\/div>|>.?and )/ms', $html, 1), 1) as $c)
array_push($arr['country'], $c);
if($arr['title_id'] != "") $arr['media_images'] = $this->getMediaImages($arr['title_id']);
return $arr;
}
// Scan all Release Dates
function getReleaseDates($html){
$releaseDates = array();
foreach($this->match_all('/<tr>(.*?)<\/tr>/ms', $this->match('/Date<\/th><\/tr>(.*?)<\/table>/ms', $html, 1), 1) as $r)
{
$country = trim(strip_tags($this->match('/<td><b>(.*?)<\/b><\/td>/ms', $r, 1)));
$date = trim(strip_tags($this->match('/<td align="right">(.*?)<\/td>/ms', $r, 1)));
array_push($releaseDates, $country . " = " . $date);
}
return $releaseDates;
}
// Scan all AKA Titles
function getAkaTitles($html, &$usa_title){
$akaTitles = array();
foreach($this->match_all('/<tr>(.*?)<\/tr>/msi', $this->match('/Also Known As(.*?)<\/table>/ms', $html, 1), 1) as $m)
{
$akaTitleMatch = $this->match_all('/<td>(.*?)<\/td>/ms', $m, 1);
$akaTitle = trim($akaTitleMatch[0]);
$akaCountry = trim($akaTitleMatch[1]);
array_push($akaTitles, $akaTitle . " = " . $akaCountry);
if ($akaCountry != '' && strrpos(strtolower($akaCountry), "usa") !== false) $usa_title = $akaTitle;
}
return $akaTitles;
}
// Collect all Media Images
function getMediaImages($titleId){
$url = "http://www.imdb.com/title/" . $titleId . "/mediaindex";
$html = $this->geturl($url);
$media = array();
$media = array_merge($media, $this->scanMediaImages($html));
foreach($this->match_all('/<a href="\?page=(.*?)">/ms', $this->match('/<span style="padding: 0 1em;">(.*?)<\/span>/ms', $html, 1), 1) as $p)
{
$html = $this->geturl($url . "?page=" . $p);
$media = array_merge($media, $this->scanMediaImages($html));
}
return $media;
}
// Scan all media images
function scanMediaImages($html){
$pics = array();
foreach($this->match_all('/src="(.*?)"/ms', $this->match('/<div class="thumb_list" style="font-size: 0px;">(.*?)<\/div>/ms', $html, 1), 1) as $i)
{
array_push($pics, preg_replace('/_V1\..*?.jpg/ms', "_V1._SY0.jpg", $i));
}
return $pics;
}
// ************************[ Extra Functions ]******************************
function geturl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$ip=rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip"));
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/".rand(3,5).".".rand(0,3)." (Windows NT ".rand(3,5).".".rand(0,2)."; rv:2.0.1) Gecko/20100101 Firefox/".rand(3,5).".0.1");
$html = curl_exec($ch);
curl_close($ch);
return $html;
}
function match_all($regex, $str, $i = 0)
{
if(preg_match_all($regex, $str, $matches) === false)
return false;
else
return $matches[$i];
}
function match($regex, $str, $i = 0)
{
if(preg_match($regex, $str, $match) == 1)
return $match[$i];
else
return false;
}
}
?>
This really shouldn't be done in jQuery, and you could still use a few lessons in being clear with what you're looking for, but a question is a question, and here is my answer:
$('th').hide();
var $titlerow = $('tr td:first'),
$yearrow = $('tr:eq(1) td:first'),
title = $titlerow.text(),
year = $yearrow.text();
$titlerow.text(title + ' - ' + year);
$yearrow.remove();
Some things to note:
You should not be doing this is jQuery. You should rearrange your PHP. If the code is copy/pasted, then I suggest reading through it. I'll be honest, I didn't read a single line of what you posted, as it was irrelevant to a client-side question after you give a link.
You should be sure to include jQuery in your site. It is not on the page you linked to. Otherwise, the code I provided will not work.
You should put the above code in document ready. I left that last bit somewhat obfuscated. Reason being is that if you don't understand any of this bullet point, some googling of the terms in it will do you good.
I have a little regex script in PHP that made clickable all my links from a string that looks like
function clickable_link($text)
{
$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
$ret = ' ' . $text;
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?#\[\]+]*)#is", "\\1\\2", $ret);
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?#\[\]+]*)#is", "\\1\\2", $ret);
$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)#([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1\\2#\\3", $ret);
return $ret;
}
and works fine, but i would like a small adjustment, like to check when its a YouTube link to not make him as
<a href=youtube>youtube</a>
but rather (if there is an youtube link) as
<iframe width="425" height="349" src="http://www.youtube.com/embed/youtube" frameborder="0" allowfullscreen></iframe>
and
<img src="link" />
if it is an image.
Any help would be appreciated.
I have wrote a little script for all of that, but its too SLOW!!!!!!!!!
<?php
function MakeContentInteractive($string)
{
$order = array("<br>", "<br/>", "<br />");
$replace = ' <br/> ';
$string = str_replace($order, $replace, $string);
$firstImageSetted = false;
$firstImage = "";
$allval = "";
$pieces = explode(" ", $string);
$regex = "^(((ht|f)tp(s?))\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk|co|tk)(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$^"; // SCHEME
$i=0;
foreach($pieces as $val)
{
echo $val."<hr>";
$i++;
$url = $val;
$url = str_replace(" ", "+", $url);
$strlen = strlen($url);
$ext = substr($val,$strlen-4,$strlen);
$random = rand(1000000,9000000);
if(preg_match($regex, $url))
{
/*CHECK IF IS YOUTUBE*/
$pos = strpos($url,"youtube.com");
if ($pos !== false)
{
//retrive video from link
$videoLink = $val;
$videoLinkPharser = $videoLink;
$videoLinkPharser = substr($videoLinkPharser, 2, 42);
$vid = substr($videoLinkPharser, -11, 42);
//check if youtube link is valid
$youtubeId = $vid;
// Check if youtube video item exists by the existance of the the 200 response
$headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $vid);
if (!strpos($headers[0], '200'))
{
$valid = 0;
}
else
{
$isYoutube = 1;
$valid = 1;
$code = '<div id="YoutubeLink"><iframe width="425" height="349" src="http://www.youtube.com/embed/'.$vid.'" frameborder="0" allowfullscreen></iframe></div>';
$allval = $allval.$code;
}
}
if(!$isYoutube == 1)
{
$url=trim($url);
/*CHECK IF IS PICTURE*/
$mime = getimagesize($url);
$mime = $mime['mime'];
if($mime == "image/gif" or $mime == "image/jpeg" or $mime == "image/png")
{
echo $url;
if(exif_imagetype($url) == IMAGETYPE_GIF and $ext == ".gif")
{
$isPicture = 1;
$filename =$random.basename($url);
$code = '<div id="CategoryPicture"><img src="'.$val.'" width="100" height="100" /><div>';
$allval = $allval.$code;
if($firstImageSetted == false)
{
$firstImage=$val;
$firstImageSetted = true;
}
}
if(exif_imagetype($url) == IMAGETYPE_JPEG and $ext == ".jpg")
{
$isPicture = 1;
$filename =$random.basename($url);
$code = '<div id="CategoryPicture"><img src="'.$val.'" width="100" height="100" /><div>';
$allval = $allval.$code;
if($firstImageSetted == false)
{
$firstImage=$val;
$firstImageSetted = true;
echo "JPG!";
}
}
if(exif_imagetype($url) == IMAGETYPE_PNG and $ext == ".png")
{
$isPicture = 1;
$filename =$random.basename($url);
$code = '<div id="CategoryPicture"><img src="'.$val.'" width="100" height="100" /><div>';
$allval = $allval.$code;
if($firstImageSetted == false)
{
$firstImage=$val;
$firstImageSetted = true;
}
}
}
}
/*IF not YOUTUBE or PICTURE then it's a link*/
if(!$isYoutube == 1 and !$isPicture == 1)
{
$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $url);
$ret = ' ' . $text;
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?#\[\]+]*)#is", "\\1\\2", $ret);
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?#\[\]+]*)#is", "\\1\\2", $ret);
$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)#([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1\\2#\\3", $ret);
$code = ''.$url.'';
$allval = $allval.$ret;
}
$isYoutube = 0;
$isPicture = 0;
}
else
{
$allval = $allval.$val;
}
}
echo "and the first image is: ".$firstImage."<br/>";
return $allval;
}
?>
And the slow part is when checks the image with exif and getimage size ( 3 seconds per picture !!!) How can i solve that???
Maybe add
$ret = preg_replace("#http\://www.youtube.com/watch\?v=([a-z0-9-_])+(&feature=[a-z_]*)*#is",
'<iframe width="425" height="349" src="http://www.youtube.com/embed/\1" frameborder="0" allowfullscreen></iframe>');
for Youtube and
$ret = preg_replace("#https?\://[a-z0-9\-.]*/[^\s]+((\.jpg)|(\.jpeg)|(\.png)|(\.gif)|(\.bmp))#is",
'<img src="\0" />');
for images. But you better do all replacements with one call to avoid replacing already replaced links. preg_replace can take arrays as pattern and replacement args.
But you can't be sure if the URL links to an image until you get a server response from it. You can only suggest that if a link ends with ".jpg", ".jpeg", ".gif", ".bmp" then it may be image. But it can be something like "http://www.google.com/search?q=trollface.jpg" which ends with ".jpg" but is not an image. You can use CURL to check such links but this may be a productivity issue.
EDIT: OK, there's a problem with your updated code. The script is so slow because you send requests to other servers and the main part of delay is awating for their response. First, I think it's not necessary to check if video is present on youtube when you have link like http://www.youtube.com/watch?v=blahblah&feature=blah . You just can take the code blahblah and embed it. If there's no such video, then youtube will tell us about it, this is the problem of the person who posted that link. I think the preg_replace which I wrote is enough.
Second, you call image processing functions several times for the same URL. And each time the image must be downloaded from other server. You should request the server only once -- to download the image (or whatever will be the response) to temporary file and then pass it's path instead of URL to image functions.
i have a small problem in figuring out a path to a image var.
here is what happens. this is the image tag:
<img src="http://www.xxx.info/wp-content/uploads/http://ecx.images-amazon.com/images/I/51AV8B7CT2L._SL160_.jpg" class="attachment-135x135 wp-post-image" alt="Clean & Sober" title="Clean & Sober">
and this is how i would like it to be, without the http://www.xxx.info/wp-content/uploads/:
<img src="http://ecx.images-amazon.com/images/I/51AV8B7CT2L._SL160_.jpg" class="attachment-135x135 wp-post-image" alt="Clean & Sober" title="Clean & Sober">
here is the wordpress code:
<?php $thumb = '';
$width = 135;
$height = 135;
$classtext = '';
$titletext = get_the_title();
$thumbnail = get_thumbnail($width,$height,$classtext,$titletext,$titletext,false,'Entry');
$thumb = $thumbnail["thumb"]; ?>
<?php print_thumbnail($thumb, $thumbnail["use_timthumb"], $titletext, $width, $height, $classtext); ?>
more related functions:
/* this function prints thumbnail from Post Thumbnail or Custom field or First post image */
function print_thumbnail($thumbnail = '', $use_timthumb = true, $alttext = '', $width = 100, $height = 100, $class = '', $echoout = true, $forstyle = false, $resize = true, $post='') {
if ( $post == '' ) global $post;
$output = '';
$thumbnail_orig = $thumbnail;
$thumbnail = et_multisite_thumbnail($thumbnail);
$cropPosition = get_post_meta($post->ID, 'etcrop', true) ? get_post_meta($post->ID, 'etcrop', true) : '';
if ($cropPosition <> '') $cropPosition = '&a=' . $cropPosition;
if ($forstyle === false) {
if ($use_timthumb === false) {
$output = $thumbnail_orig;
} else {
$output = '<img src="'.get_bloginfo('template_directory').'/timthumb.php?src='.$thumbnail.'&h='. $height .'&w='. $width .'&zc=1&q=90'.$cropPosition.'"';
if ($class <> '') $output .= " class='$class' ";
$output .= " alt='$alttext' width='$width' height='$height' />";
if (!$resize) $output = $thumbnail;
}
} else {
$output = $thumbnail;
if ($use_timthumb === false) {
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $output, $matches);
$output = $matches[1][0];
} else {
$output = get_bloginfo('template_directory').'/timthumb.php?src='.$output.'&h='.$height.'&w='.$width.'&q=90&zc=1'.$cropPosition;
}
}
if ($echoout) echo $output;
else return $output;
}
this is what i get returned $output = $thumbnail_orig; in the image tag.
i know that there should be a var for http://www.xxx.info/wp-content/uploads/
and another one for http://ecx.images-amazon.com/images/I/51AV8B7CT2L._SL160_.jpg
i want to remove the the website path to uploads.
i cant seem to figure it out,
All help appreciated,
Thanks
I might be wrong or misunderstanding the question, but I thought setting the path in WP is as simple as editing it in the admin panel, under settings, no?
DC