Change Output of PHP Script to use POST Method - php

Bear with my inexperience here, but can anyone point me in the right direction for how I can change the PHP script below to output each variable that is parsed from the XML file (title, link, description, etc) as a POST method instead of just to an HTML page?
<?php
$html = "";
$url = "http://api.brightcove.com/services/library?command=search_videos&any=tag:SMGV&output=mrss&media_delivery=http&sort_by=CREATION_DATE:DESC&token= // this is where the API token goes";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces
for($i = 0; $i < 80; $i++){
$title = $xml->channel->item[$i]->video;
$link = $xml->channel->item[$i]->link;
$title = $xml->channel->item[$i]->title;
$pubDate = $xml->channel->item[$i]->pubDate;
$description = $xml->channel->item[$i]->description;
$titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
$html .= "<h3>$title</h3>$description<p>$pubDate<p>$link<p>Video ID: $titleid<p>
<iframe width='480' height='270' src='http://link.brightcove.com/services/player/bcpid3742068445001?bckey=AQ~~,AAAABvaL8JE~,ufBHq_I6FnyLyOQ_A4z2-khuauywyA6P&bctid=$titleid&autoStart=false' frameborder='0'></iframe><hr/>";/* this embed code is from the youtube iframe embed code format but is actually using the embedded Ooyala player embedded on the Campus Insiders page. I replaced any specific guid (aka video ID) numbers with the "$guid" variable while keeping the Campus Insider Ooyala publisher ID, "eb3......fad" */
}
echo $html;
?>
#V.Radev Here's another PHP script using cURL that I think will work with the API I'm trying to send data to:
<?PHP
$url = 'http://api.brightcove.com/services/post';
//open connection
$ch = curl_init($url);
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, '$title,$descripton,$url' . stripslashes($_POST['$title,$description,$url']));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
// Enable for Charles debugging
//curl_setopt($ch,CURLOPT_PROXY, '127.0.0.1:8888');
$result = curl_exec($ch);
curl_close($ch);
print $result;
?>
My question is, how can I pass the variables from my feed parsing script (title, description, URL) to this new script?
I have this code from Brightcove, can I just output the variables from my parser script and send to this PHP script so that the data goes to the API?
<?php
// This code example uses the PHP Media API wrapper
// For the PHP Media API wrapper, visit http://docs.brightcove.com/en/video-cloud/open-source/index.html
// Include the BCMAPI Wrapper
require('bc-mapi.php');
// Instantiate the class, passing it our Brightcove API tokens (read, then write)
$bc = new BCMAPI(
'[[READ_TOKEN]]',
'[[WRITE_TOKEN]]'
);
// Create an array of meta data from our form fields
$metaData = array(
'name' => $_POST['bcVideoName'],
'shortDescription' => $_POST['bcShortDescription']
);
// Move the file out of 'tmp', or rename
rename($_FILES['videoFile']['tmp_name'], '/tmp/' . $_FILES['videoFile']['name']);
$file = '/tmp/' . $_FILES['videoFile']['name'];
// Create a try/catch
try {
// Upload the video and save the video ID
$id = $bc->createMedia('video', $file, $metaData);
echo 'New video id: ';
echo $id;
} catch(Exception $error) {
// Handle our error
echo $error;
die();
}
?>

Post is a request method to access a specific page or resource. With echo you are sending data which means that you are responding. In this page you can only add response headers and access it with a request method such as post, get, put etc.
Edit for API request as mentiond in the comments:
$curl = curl_init('your api url');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $your_data_to_send);
$result_from_api = curl_exec($curl);
curl_close($curl);

Related

Youtube get video title from id

I understand this may have been answered somewhere, but after looking and looking through numerous questions/answers and other websites, I'm unable to find a suitable answer.
I'm trying to create a page, which will show some video from Youtube. It will show the image, and title. I've managed to do both of these, although i'm having problems with the title. With the code i'm using, it is awfully slow at loading. I assume because of it loading the actual website just to get the title.
This is what i'm using to get the titles currently.
function get_youtube_id($url){
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
return $my_array_of_vars['v'];
}
function get_youtube_title($video_id){
$url = "http://www.youtube.com/watch?v=".$video_id;
$page = file_get_contents($url);
$doc = new DOMDocument();
$doc->loadHTML($page);
$title_div = $doc->getElementById('eow-title');
$title = $title_div->nodeValue;
return $title;
}
So, how would the best way to get a youtube title by the id. The code I have does work, but it also makes the page load very very slow.
Thanks
Here is a simple way to do it using PHP and no library. YouTube already allows you to retrieve video detail information in the JSON format, so all you need is a simple function like this:
function get_youtube_title($ref) {
$json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
$details = json_decode($json, true); //parse the JSON into an array
return $details['title']; //return the video title
}
The function parameter being the video ID. You could also add a second parameter asking for a specific detail and change the function name so you could retrieve any data from the JSON that you would like.
EDIT:
If you would like to retrieve any piece of information from the returned video details you could use this function:
function get_youtube_details($ref, $detail) {
if (!isset($GLOBALS['youtube_details'][$ref])) {
$json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
$GLOBALS['youtube_details'][$ref] = json_decode($json, true); //parse the JSON into an array
}
return $GLOBALS['youtube_details'][$ref][$detail]; //return the requested video detail
}
If you request different details about the same video, the returned JSON data is stored in the $GLOBALS array to prevent necessary calls to file_get_contents.
Also, allow_url_fopen will have to be on in your php.ini for file_get_contents to work, which may be a problem on shared hosts.
You can use Open Graph
Checkout This Link
<?php
require_once('OpenGraph.php');
function get_youtube_title($video_id){
$url = "http://www.youtube.com/watch?v=".$video_id;
$graph = OpenGraph::fetch($url);
// You can get title from array
return $graph->title;
}
It's been 5 years, but my script bellow could be useful.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.youtube.com/watch?v=YOUTUBEID");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$document = htmlspecialchars($output);
curl_close($ch);
$line = explode("\n", $document);
$judul = "";
foreach($line as $strline){
preg_match('/\<title\>(.*?)\<\/title\>/s', $strline, $hasil);
if (!isset($hasil[0]) || $hasil[0] == "") continue;
$title = str_replace(array("<title>", "</title>"), "", $hasil[0]);
}
echo $title;

Output PHP Parser Script Variables to PHP form via Sessions

New to PHP, so bear with me...
I'm trying to send/make available the output variables from this simpleXml parser script to this other PHP file, which is supposed to send data to Brightcove's Media API.
Sending Script:
<?php
session_name("FeedParse");
session_start();
$_SESSION['bcName'] = $title;
$_SESSION['shortDescription'] = $description;
$_SESSION['remoteUrl'] = $videoFile;
$html = "";
$url = "http://feeds.nascar.com/feeds/video?command=search_videos&media_delivery=http&custom_fields=adtitle%2cfranchise&page_size=100&sort_by=PUBLISH_DATE:DESC&token=217e0d96-bd4a-4451-88ec-404debfaf425&any=franchise:%20Preview%20Show&any=franchise:%20Weekend%20Top%205&any=franchise:Up%20to%20Speed&any=franchise:Press%20Pass&any=franchise:Sprint%20Cup%20Practice%20Clips&any=franchise:Sprint%20Cup%20Highlights&any=franchise:Sprint%20Cup%20Final%20Laps&any=franchise:Sprint%20Cup%20Victory%20Lane&any=franchise:Sprint%20Cup%20Post%20Race%20Reactions&any=franchise:All%20Access&any=franchise:Nationwide%20Series%20Qualifying%20Clips&any=franchise:Nationwide%20Series%20Highlights&any=franchise:Nationwide%20Series%20Final%20Laps&any=franchise:Nationwide%20Series%20Victory%20Lane&any=franchise:Nationwide%20Series%20Post%20Race%20Reactions&any=franchise:Truck%20Series%20Qualifying%20Clips&any=franchise:Truck%20Series%20Highlights&any=franchise:Truck%20Series%20Final%20Laps&any=franchise:Truck%20Series%20Victory%20Lane&any=franchise:Truck%20Series%20Post%20Race%20Reactions&output=mrss";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces
for($i = 0; $i < 50; $i++){ // will return the 50 most recent videos
$title = $xml->channel->item[$i]->video;
$link = $xml->channel->item[$i]->link;
$title = $xml->channel->item[$i]->title;
$pubDate = $xml->channel->item[$i]->pubDate;
$description = $xml->channel->item[$i]->description;
$titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
$m_attrs = $xml->channel->item[$i]->children($namespaces['media'])->content[0]->attributes();
$videoFile = $m_attrs["url"];
$html .= //"<h3>$title</h3>$description<p>$pubDate<p>$url<p>Video ID: $titleid<p>
print $title;
print $description;
print $videoFile;
// echo $html;/* tutorial for this script is here https://www.youtube.com/watch?v=4ZLZkdiKGE0 */
}
//http://support.brightcove.com/en/video-cloud/docs/media-write-api-php-example-upload-video
?>
Receiving Script:
<?php
session_start();
$title = $_SESSION['bcName'];
$description = $_SESSION['shortDescription'];
$videoFile = $_SESSION['remoteUrl'];
// Instantiate the Brightcove class
$bc = new Brightcove(
'//readtoken//', //Read Token BC
'//writetoken//' //Write Token BC
);
// Set the data for the new video DTO using the form values
$metaData = array(
'$title' => $_POST['bcName'],
'$description' => $_POST['bcShortDescription'],
);
//changed all the code below to what i think works for remoteUrl and URLs as opposed to actual video files
// Rename the file to its original file name (instead of temp names like "a445ertd3")
$url = $_URL['remoteUrl'];
//rename($url['tmp_name'], '/tmp/' . $url['name']);
//$url = '/tmp/' . $url['name'];
// Send the file to Brightcove
//Actually, this has been changed to send URL to BC, not file
echo $bc->createVideo($url,$metaData);
class Brightcove {
public $token_read = 'UmILcDyAFKzjtWO90HNzc67X-wLZK_OUEZliwd9b3lZPWosBPgm1AQ..'; //Read Token from USA Today Sports BC
public $token_write = 'svP0oJ8lx3zVkIrMROb6gEkMW6wlX_CK1MoJxTbIajxdn_ElL8MZVg..'; //Write Token from USA Today Sports BC
public $read_url = 'http://api.brightcove.com/services/library?';
public $write_url = 'http://api.brightcove.com/services/post';
public function __construct($token_read, $token_write = NULL ) {
$this->token_read = $token_read;
$this->token_write = $token_write;
}
public function createVideo($url = NULL, $meta) {
$request = array();
$post = array();
$params = array();
$video = array();
foreach($meta as $key => $value) {
$video[$key] = $value;
}
$params['token'] = $this->token_write;
$params['video'] = $video;
$post['method'] = 'create_video';
$post['params'] = $params;
$request['json'] = json_encode($post);
if($file) {
$request['file'] = '#' . $file;
}
// Utilize CURL library to handle HTTP request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->write_url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_VERBOSE, TRUE );
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 300);
curl_setopt($curl, CURLOPT_TIMEOUT, 300);
$response = curl_exec($curl);
curl_close($curl);
// Responses are transfered in JSON, decode into PHP object
$json = json_decode($response);
// Check request error code and re-call createVideo if request
// returned a 213 error. A 213 error occurs when you have
// exceeded your allowed number of concurrent write requests
if(isset($json->error)) {
if($json->error->code == 213) {
return $this->createVideo($url, $meta);
} else {
return FALSE;
}
} else {
return $response;
}
}
}
?>​
Did I set up sessions to work correctly here? Any ideas on why the receiving PHP script isn't picking up the data/variables outputted by the PHP feed parser script?
In your sending script, it looks like you're setting the session variables at the beginning of the script and you're expecting them to get updated whenever the local variable changes. This won't happen with the way you've written it.
You could make this happen by assigning the variables by reference, by putting an ampersand (&) before the local variable name, but this can get kinda tricky in some scenarios, and it might be best to skip that headache and instead just update the session variable directly.
However, another issue is that you're attempting to store multiple values (50, as indicated by the code comments) into a scalar session variable. So every time your loop iterates, it would overwrite the previous value. Perhaps what would be better would be to use an array structure:
<?php
session_name("FeedParse");
session_start();
$_SESSION['videos'] = array(); // initialize a session variable 'videos' to be an array
$url = "http://feeds.nascar.com/feeds/video?command=search_videos&media_delivery=http&custom_fields=adtitle%2cfranchise&page_size=100&sort_by=PUBLISH_DATE:DESC&token=217e0d96-bd4a-4451-88ec-404debfaf425&any=franchise:%20Preview%20Show&any=franchise:%20Weekend%20Top%205&any=franchise:Up%20to%20Speed&any=franchise:Press%20Pass&any=franchise:Sprint%20Cup%20Practice%20Clips&any=franchise:Sprint%20Cup%20Highlights&any=franchise:Sprint%20Cup%20Final%20Laps&any=franchise:Sprint%20Cup%20Victory%20Lane&any=franchise:Sprint%20Cup%20Post%20Race%20Reactions&any=franchise:All%20Access&any=franchise:Nationwide%20Series%20Qualifying%20Clips&any=franchise:Nationwide%20Series%20Highlights&any=franchise:Nationwide%20Series%20Final%20Laps&any=franchise:Nationwide%20Series%20Victory%20Lane&any=franchise:Nationwide%20Series%20Post%20Race%20Reactions&any=franchise:Truck%20Series%20Qualifying%20Clips&any=franchise:Truck%20Series%20Highlights&any=franchise:Truck%20Series%20Final%20Laps&any=franchise:Truck%20Series%20Victory%20Lane&any=franchise:Truck%20Series%20Post%20Race%20Reactions&output=mrss";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces
for($i = 0; $i < 50; $i++){ // will return the 50 most recent videos
$m_attrs = $xml->channel->item[$i]->children($namespaces['media'])->content[0]->attributes();
// on each loop iteration, create a new array structure with the video info in it and
// push it onto the 'video' array session variable
$video = array(
'bcName' => $xml->channel->item[$i]->video,
'shortDescription' => $xml->channel->item[$i]->description,
'remoteUrl' => $m_attrs["url"],
);
$_SESSION['videos'][] = $video;
}
Then, on your receiving script, you'll loop through $_SESSION['videos']:
<?php
session_start();
// Instantiate the Brightcove class
$bc = new Brightcove(
'UmILcDyAFKzjtWO90HNzc67X-wLZK_OUEZliwd9b3lZPWosBPgm1AQ..', //Read Token from USA Today Sports BC
'svP0oJ8lx3zVkIrMROb6gEkMW6wlX_CK1MoJxTbIajxdn_ElL8MZVg..' //Write Token from USA Today Sports BC
foreach ((array)$_SESSION['videos'] as $video) {
$title = $video['bcName'];
$description = $video['shortDescription'];
$videoFile = $video['remoteUrl'];
// The code below this line may need to be adjusted. It does not seem quite right.
// Are you actually sending anything to this script via POST? Or should those just
// be the values we set above?
// What is $_URL? Should that just be the $videoFile value?
// Set the data for the new video DTO using the form values
$metaData = array(
'$title' => $_POST['bcName'],
'$description' => $_POST['bcShortDescription'],
);
//changed all the code below to what i think works for remoteUrl and URLs as opposed to actual video files
// Rename the file to its original file name (instead of temp names like "a445ertd3")
$url = $_URL['remoteUrl'];
//rename($url['tmp_name'], '/tmp/' . $url['name']);
//$url = '/tmp/' . $url['name'];
// Send the file to Brightcove
//Actually, this has been changed to send URL to BC, not file
echo $bc->createVideo($url,$metaData);
}
IMPORTANT NOTE:
Keep in mind that this will call the API once for each video in the session (sounds like up to 50 each time). So you'll be making 50 cURL requests on each run of this script. That seems a bit heavy, but perhaps that's expected. It would be worth investigating if their API allows you to compile the data into one call and send it all up at once, as opposed to connecting, sending the data, parsing the response, and disconnecting, 50 times.

Create a "like" for a user with Instagram API

So, I'm working with the Instagram API, but I cannot figure out how to create a like (on a photo) for the logged in user.
So my demo app is currently displaying the feed of a user, and it's requesting the permission to like and comment on behalf of that user. I'm using PHP and Curl to make this happen, creds to some guide I found on the internet:
<?php
if($_GET['code']) {
$code = $_GET['code'];
$url = "https://api.instagram.com/oauth/access_token";
$access_token_parameters = array(
'client_id' => '*MY_CLIENT_ID*',
'client_secret' => '*MY_CLIENT_SECRET*',
'grant_type' => 'authorization_code',
'redirect_uri' => '*MY_REDIRECT_URI*',
'code' => $code
);
$curl = curl_init($url); // we init curl by passing the url
curl_setopt($curl,CURLOPT_POST,true); // to send a POST request
curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_parameters); // indicate the data to send
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // to stop cURL from verifying the peer's certificate.
$result = curl_exec($curl); // to perform the curl session
curl_close($curl); // to close the curl session
$arr = json_decode($result,true);
$pictureURL = 'https://api.instagram.com/v1/users/self/feed?access_token='.$arr['access_token'];
// to get the user's photos
$curl = curl_init($pictureURL);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$pictures = curl_exec($curl);
curl_close($curl);
$pics = json_decode($pictures,true);
// display the url of the last image in standard resolution
for($i = 0; $i < 17; $i++) {
$id = $pics['data'][$i]['id'];
$lowres_pic = $pics['data'][$i]['images']['low_resolution']['url'];
$username = $pics['data'][$i]['user']['username'];
$profile_pic = $pics['data'][$i]['user']['profile_picture'];
$created_time = $pics['data'][$i]['created_time'];
$created_time = date('d. M - h:i', $created_time);
$insta_header = '<div class="insta_header"><div class="insta_header_pic"><img src="'.$profile_pic.'" height="30px" width="30px"/></div><div class="insta_header_name">'.$username.'</div><div class="insta_header_date">'.$created_time.'</div></div>';
$insta_main = '<div class="insta_main"><img src="'.$lowres_pic.'" /></div>';
$insta_footer = '<div class="insta_footer"><div class="insta_footer_like"><button onClick="insta_like(\''.$id.'\')"> Like </button></div><div class="insta_footer_comment"><form onSubmit="return insta_comment(\''.$id.'\')"><input type="text" id="'.$id.'" value="Comment" /></form></div></div>';
echo '<div class="insta_content">'. $insta_header . $insta_main . $insta_footer .'</div>';
}
}
?>
Now, it might be a stupid question, but how do I make a like on a particular photo on behalf of the user? I'm used to using JavaScript to these kinds of things, therefore I've setup the Like-button with a JS function (which does not exist). But since the Instagram thing have been using Curl and PHP, I'm guessing I have to do the same thing here? I have no experience with Curl, and I do not understand how it works. It would be great if someone could give me a headsup on that as well. But first off, the liking. If it's possible to do it with JS, I'd be very glad. If not, please show me how to do it with PHP and Curl.
Here's a link to the Instagram developers site, which contain the URL you should send a POST request to http://instagram.com/developer/endpoints/likes/.
And if you're not to busy, I'd be really glad if you could show me how to make a comment on behalf of a user as well :)
Thanks in advance.
Aleksander.

fetch all youtube videos using curl

I'm a beginner at PHP. I have one task in my project, which is to fetch all videos from a YouTube link using curl in PHP. Is it possible to show all videos from YouTube?
I found this code with a Google search:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.youtube.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
echo $contents;
curl_close ($ch);
?>
It shows the YouTube site, but when I click any video it will not play.
You can get data from youtube oemebed interface in two formats Xml and Json which returns metadata about a video:
http://www.youtube.com/oembed?url={videoUrlHere}&format=json
Using your example, a call to:
http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=B4CRkpBGQzU&format=json
So, You can do like this:
$url = "Your_Youtube_video_link";
Example :
$url = "http://www.youtube.com/watch?v=m7svJHmgJqs"
$youtube = "http://www.youtube.com/oembed?url=" . $url. "&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
$result = json_decode($return, true);
echo $result['html'];
Try it...Hope it will help you.
You could use curl to retrieve the Google main page (or an alternative page) and parse the returned html using a library such as html5lib. If you wanted to try this approach the first step could be to 'view source' on the relevant page and look at how the links are structured.
A more elegant way to approach the problem could be to use the Youtube API (a way to interact with the Youtube system), which may allow you to retrieve the links directly. e.g it may be possible to just ask the Youtube API to send you the links. Try this.
You can also get all youtube's channel videos using file_get_contents
bellow is sample and working code
<?php
$Youtube_API_Key = ""; // you can obtain api key : https://developers.google.com/youtube/registering_an_application
$Youtube_channel_id = "";
$TotalVideso = 50; // 50 is max , if you want more video you need Youtube secret key.
$order= "date"; ////allowed order : date,rating,relevance,title,videocount,viewcount
$url = "https://www.googleapis.com/youtube/v3/search?key=".$Youtube_API_Key."&channelId=".$Youtube_channel_id."&part=id&order=".$order."&maxResults=".$TotalVideso."&format=json";
$data = file_get_contents($url);
$JsonDecodeData=json_decode($data, true);
print_r($data);
?>

PHP - Run function for each file in a directory passing two parameters

I should start by saying I have no php experience what so ever, but I know this script can't be that ambitious.
I'm using Wordpress' metaWeblog API to batch the creation of several hundred posts. Each post needs a discrete title, a description, and url's for two images, the latter being custom fields.
I have been successful producing one post by manually entering data into the following file;
<?php // metaWeblog.Post.php
$BLOGURL = "http://path/to/your/wordpress";
$USERNAME = "username";
$PASSWORD = "password";
function get_response($URL, $context) {
if(!function_exists('curl_init')) {
die ("Curl PHP package not installed\n");
}
/*Initializing CURL*/
$curlHandle = curl_init();
/*The URL to be downloaded is set*/
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, false);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $context);
/*Now execute the CURL, download the URL specified*/
$response = curl_exec($curlHandle);
return $response;
}
function createPost(){
/*The contents of your post*/
$description = "post description";
/*Forming the content of blog post*/
$content['title'] = $postTitle;
$content['description'] = $description;
/*Pass custom fields*/
$content['custom_fields'] = array(
array( 'key' => 'port_thumb_image_url', 'value' => "$imagePath" ),
array( 'key' => 'port_large_image_url', 'value' => "$imagePath" )
);
/*Whether the post has to be published*/
$toPublish = false;//false means post will be draft
$request = xmlrpc_encode_request("metaWeblog.newPost",
array(1,$USERNAME, $PASSWORD, $content, $toPublish));
/*Making the request to wordpress XMLRPC of your blog*/
$xmlresponse = get_response($BLOGURL."/xmlrpc.php", $request);
$postID = xmlrpc_decode($xmlresponse);
echo $postID;
}
?>
In an attempt to keep this short, here is the most basic example of the script that iterates through a directory and is "supposed" to pass the variables $postTitle, and $imagePath and create the posts.
<?php // fileLoop.php
require('path/to/metaWeblog.Post.php');
$folder = 'foldername';
$urlBase = "images/portfolio/$folder";//truncate path to images
if ($handle = opendir("path/to/local/images/portfolio/$folder/")) {
/*Loop through files in truncated directory*/
while (false !== ($file = readdir($handle))) {
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']); // strip file extension
$postTitle = preg_replace("/\.0|\./", " ", $file_name); // Make file name suitable for post title !LEAVE!
echo "<tr><td>$postTitle</td>";
$imagePath = "$urlBase/$file";
echo " <td>$urlBase/$file</td>";
createPost($postTitle, $imagePath);
}
closedir($handle);
}
?>
It's supposed to work like this,
fileLoop.php opens the directory and iterates through each file
for each file in the directory, a suitable post title(postTitle) is created and a url path(imagePath) to the server's file is made
each postTitle and imagePath is passed to the function createPost in metaWeblog.php
metaWeblog.php creates the post and passes back the post id to finish creating the table row for each file in the directory.
I've tried declaring the function in fileLoop.php, I've tried combining the files completely. It either creates the table with all files, or doesn't step through the directory that way. I'm missing something, I know it.
I don't know how to incorporate $POST_ here, or use sessions as I said I'm very new to programming in php.
You need to update your declaration of the createPost() function so that it takes into account the parameters you are attempting to send it.
So it should be something like this:
function createPost($postTitle, $imagePath){
/*The contents of your post*/
$description = "post description";
...
}
More information about PHP function arguments can be found on the associated manual page.
Once this has been remedied you can use CURL debugging to get more information about your external request. To get more information about a CURL request try setting the following options:
/*Initializing CURL*/
$curlHandle = curl_init();
/*The URL to be downloaded is set*/
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, false);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $context);
curl_setopt($curlHandle, CURLOPT_HEADER, true); // Display headers
curl_setopt($curlHandle, CURLOPT_VERBOSE, true); // Display communication with server
/*Now execute the CURL, download the URL specified*/
$response = curl_exec($curlHandle);
print "<pre>\n";
print_r(curl_getinfo($ch)); // get error info
echo "\n\ncURL error number:" .curl_errno($ch); // print error info
echo "\n\ncURL error:" . curl_error($ch);
print "</pre>\n";
The above debug example code is from eBay's help pages.
It should show you if Wordpress is rejecting the request.

Categories