Friday, 16 August 2013
Code to make other site image to get stored in your wordpress database as well as making other site images to your wordpress post featured image
$upload_dir = wp_upload_dir();
$image_data = file_get_contents("Image URL for other site");
$filename = basename($image_url);
if(wp_mkdir_p($upload_dir['path']))
$file = $upload_dir['path'] . '/' . $filename;
else
$file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id , $attach_id );
wp_update_attachment_metadata will make the image to get stored in your database
set_post_thumbnail will make the image to get featured for the post
$post_id - will be ID of your post, for example if you just want to make your post id 5 to get featured image then just replace the variable $post_id with 5
substr in php is not removing characters?
I had a similar problem before and rectified using mb_substr, for demo please check the below code
$then_truncate_the_value=mb_substr($remove_html_first , 0, 123);
How to scrap the titles of a Wordpress site using CURL php?
$curl1 = curl_init();
curl_setopt($curl1, CURLOPT_URL, 'Your URL');
curl_setopt($curl1, CURLOPT_HEADER, false);
curl_setopt($curl1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl1, CURLOPT_FOLLOWLOCATION,true);
curl_setopt($curl1, CURLOPT_ENCODING,"");
curl_setopt($curl1, CURLOPT_USERAGENT, "spider");
curl_setopt($curl1, CURLOPT_AUTOREFERER,true);
$result1 = curl_exec($curl1); curl_close($curl1);
## get the title
preg_match_all('your h1 tag with calss', $result1, $matches1, PREG_OFFSET_CAPTURE);
preg_match('/your anchor tag/', $matches1[0][0][0], $set1);
$my_title=$set1[2];
1) Initialize the CURL
2) Enter the URL
3) Check whether the wordpress site comes with the h1 tag and with the same class i declared here, else use the correct one
4) I dont want the link tag so i removed the <--a---> tag, and finally we will have the result--a--->
How to get images for a URL through php?
We can use many concepts for this eithe we can use DOM or CURL or anything. Lets see a simple example on how to use DOM concept
$doc = new DOMDocument();
$doc->loadHTML('Your URL');
$imageTags = $doc->getElementsByTagName('img');
foreach($imageTags as $tag) {
$img_src= $tag->getAttribute('src');
}
By this we can get all the image tag in the particular URL, you can write separate scripts for Image types too.
$doc = new DOMDocument();
$doc->loadHTML('Your URL');
$imageTags = $doc->getElementsByTagName('img');
foreach($imageTags as $tag) {
$img_src= $tag->getAttribute('src');
}
By this we can get all the image tag in the particular URL, you can write separate scripts for Image types too.
Friday, 12 July 2013
Search lists from Youtube, Dailymotion, Google and Metacafe using PHP
Youtube: For youtube you need to down the files from google-api-php-client and please use this below demo file
$htmlBody = <<
Search Term:
Max Results:
END;
if ($_GET['q'] && $_GET['maxResults']) {
// Call set_include_path() as needed to point to your client library.
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_YouTubeService.php';
/* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
Google APIs Console
Please ensure that you have enabled the YouTube Data API for your project. */
$DEVELOPER_KEY = 'put your api key here';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
$youtube = new Google_YoutubeService($client);
try {
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'q' => $_GET['q'],
'maxResults' => $_GET['maxResults'],
));
$videos = '';
$channels = '';
$playlists = '';
//print_r($searchResponse['items']);
for($x=0;$x
echo $searchResponse['items'][$x]['id'] ['videoId'] ;
}
/*
foreach ($searchResponse['items'] as $searchResult) {
switch ($searchResult['id']['kind']) {
case 'youtube#video':
$videos .= sprintf('
%s (%s)
', $searchResult['snippet']['title'],
$searchResult['id']['videoId']);
break;
case 'youtube#channel':
$channels .= sprintf('%s (%s)
', $searchResult['snippet']['title'],
$searchResult['id']['channelId']);
break;
case 'youtube#playlist':
$playlists .= sprintf('%s (%s)
', $searchResult['snippet']['title'],
$searchResult['id']['playlistId']);
break;
}
}
$htmlBody .= <<
END;*/
} catch (Google_ServiceException $e) {
$htmlBody .= sprintf('A service error occurred:
',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('An client error occurred:
',
htmlspecialchars($e->getMessage()));
}
}
?>
YouTube Search
=================================================================
$url = "https://ajax.googleapis.com/ ajax/services/search/images?" .
"v=1.0&q=barack%20obama& userip=INSERT-USER-IP";
// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "http://localhost/#######/google.php");
$body = curl_exec($ch);
curl_close($ch);
// now, process the JSON string
$json = json_decode($body);
/*$results = array();
foreach ($json['responseData'][' results'] as $result) {
$results[] = array(
'url' => $result['url'],
'title' => $result['title'],
'content'=>$result['content']
);
}
*/
echo '
for($x=0;$x responseData->results);$x++){
echo "Result ".($x+1)."";
echo "
Image: ";
echo $json->responseData->results[$ x]->url;
echo "
echo $json->responseData->results[$ x]->url;
echo "
URL: ";
echo $json->responseData->results[$ x]->url;
echo "
VisibleURL: ";
echo $json->responseData->results[$ x]->visibleUrl;
echo "
Title: ";
echo $json->responseData->results[$ x]->title;
echo "
Content: ";
echo $json->responseData->results[$ x]->content;
echo "
";
}
// now have some fun with the results...
/*echo '
*/
//$decodedJSON = json_encode($json);
// Put everyting to the screen with var_dump;
//var_dump($decodedJSON);
// With print_r ( useful for arrays );
//print_r($decodedJSON);
/*foreach ( $json->responseData->results as $results1 )
{
echo $results1;
}*/
//print_r($json->responseData- >results);
/*$properties = get_object_vars($json);
print_r($properties);*/
//print_r($json);
?>
==================================================================
if(isset($_POST['search']))
{
$video=$_POST['video'];
//echo $video;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://www.metacafe.com/ topics/'.$video);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION,true);
$result = curl_exec($curl); curl_close($curl);
//echo $result;
//$value=preg_match_all('/< section class=\"CCol">(.*?)<\/section> /s',$result,PREG_PATTERN_ ORDER);
preg_match('/
(.*?)<\/section> /s', $result, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
}
?>
http://www.w3.org/TR/xhtml1/ DTD/xhtml1-transitional.dtd
">
http://www.w3.org/1999/ xhtml">
Search Video - Metcafe
==================================================================
$url="https://api.dailymotion. com/videos?search=facebook& fields=id,title,channel, thumbnail_medium_url";
demos/dailymotion-sdk-php- master/test.php");
$body = curl_exec($ch);
curl_close($ch);
// now, process the JSON string
$json = json_decode($body);
list) ;$x++){
echo "Result ".($x+1)."";
echo "
id: ";
echo $json->list[$x]->id;
echo "
Img: ";
echo "
";
echo "
channel: ";
echo $json->list[$x]->channel;
echo "
title: ";
echo $json->list[$x]->title;
echo "
";
}
?>
$htmlBody = <<
Search Term:
Max Results:
END;
if ($_GET['q'] && $_GET['maxResults']) {
// Call set_include_path() as needed to point to your client library.
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_YouTubeService.php';
/* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
Google APIs Console
Please ensure that you have enabled the YouTube Data API for your project. */
$DEVELOPER_KEY = 'put your api key here';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
$youtube = new Google_YoutubeService($client);
try {
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'q' => $_GET['q'],
'maxResults' => $_GET['maxResults'],
));
$videos = '';
$channels = '';
$playlists = '';
//print_r($searchResponse['items']);
for($x=0;$x
echo $searchResponse['items'][$x]['id'] ['videoId'] ;
}
/*
foreach ($searchResponse['items'] as $searchResult) {
switch ($searchResult['id']['kind']) {
case 'youtube#video':
$videos .= sprintf('
$searchResult['id']['videoId']);
break;
case 'youtube#channel':
$channels .= sprintf('
$searchResult['id']['channelId']);
break;
case 'youtube#playlist':
$playlists .= sprintf('
$searchResult['id']['playlistId']);
break;
}
}
$htmlBody .= <<
Videos
- $videos
Channels
- $channels
Playlists
- $playlists
END;*/
} catch (Google_ServiceException $e) {
$htmlBody .= sprintf('A service error occurred:
%s',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('An client error occurred:
%s',
htmlspecialchars($e->getMessage()));
}
}
?>
=================================================================
Google Image Search:
$url = "https://ajax.googleapis.com/
"v=1.0&q=barack%20obama&
// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "http://localhost/#######/google.php");
$body = curl_exec($ch);
curl_close($ch);
// now, process the JSON string
$json = json_decode($body);
/*$results = array();
foreach ($json['responseData']['
$results[] = array(
'url' => $result['url'],
'title' => $result['title'],
'content'=>$result['content']
);
}
*/
echo '
'; var_dump($json->responseData->';results); echo '
for($x=0;$x
echo "Result ".($x+1)."";
echo "
Image: ";
echo $json->responseData->results[$
echo "
echo $json->responseData->results[$
echo "
URL: ";
echo $json->responseData->results[$
echo "
VisibleURL: ";
echo $json->responseData->results[$
echo "
Title: ";
echo $json->responseData->results[$
echo "
Content: ";
echo $json->responseData->results[$
echo "
";
}
// now have some fun with the results...
/*echo '
'; var_dump($json); echo '';
*/
//$decodedJSON = json_encode($json);
// Put everyting to the screen with var_dump;
//var_dump($decodedJSON);
// With print_r ( useful for arrays );
//print_r($decodedJSON);
/*foreach ( $json->responseData->results as $results1 )
{
echo $results1;
}*/
//print_r($json->responseData-
/*$properties = get_object_vars($json);
print_r($properties);*/
//print_r($json);
?>
==================================================================
Metacafe:
if(isset($_POST['search']))
{
$video=$_POST['video'];
//echo $video;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://www.metacafe.com/
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION,true);
$result = curl_exec($curl); curl_close($curl);
//echo $result;
//$value=preg_match_all('/<
preg_match('/
print_r($matches);
}
?>
http://www.w3.org/TR/xhtml1/
">
http://www.w3.org/1999/
==================================================================
Daily Motion:
$url="https://api.dailymotion.
// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "http://localhost/jothirajan/// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$body = curl_exec($ch);
curl_close($ch);
// now, process the JSON string
$json = json_decode($body);
/*echo '
*/
for($x=0;$x'; var_dump($json); echo '';
*/
echo "Result ".($x+1)."";
id: ";
echo $json->list[$x]->id;
echo "
Img: ";
echo "
echo "
channel: ";
echo $json->list[$x]->channel;
echo "
title: ";
echo $json->list[$x]->title;
echo "
";
}
?>
Thursday, 2 May 2013
Increment date using while loop in php
$start_date = "2013-01-01";
$end_date = "2013-01-20";
$next_date = $start_date;
while(strtotime($next_date) <= strtotime($end_date))
{
echo "$next_date
";
$next_date = date ("Y-m-d", strtotime("+5 day", strtotime($next_date)));
}
Ok in for loop?
$start_date = "2013-01-01";
$end_date = "2013-01-25";
$next_date = $start_date;
for($i=0;$i<=(strtotime($next_date) <= strtotime($end_date));$i++)
{
echo "$next_date
";
$next_date = date ("Y-m-d", strtotime("+2 day", strtotime($next_date)));
}
$start_date = "2013-01-01";
$end_date = "2013-01-25";
$next_date = $start_date;
for($i=0;$i<=(strtotime($next_date) <= strtotime($end_date));$i++)
{
echo "$next_date
";
$next_date = date ("Y-m-d", strtotime("+2 day", strtotime($next_date)));
}
SUM TWO TIMES IN PHP, SUM TWO TIME VALUES IN PHP
echo sum_the_time('01:45:22', '17:27:03');
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
// return "{$hours}:{$minutes}:{$seconds}";
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
// return "{$hours}:{$minutes}:{$seconds}";
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
Subscribe to:
Posts (Atom)