i'm making a curl post to Google text to speech. I have a set of .flac files, that i want to send to Google Text to Speech service, in order to have the content wrote in a txt file.
This is the code i wrote to do this and it works:
$url = 'https://www.google.com/speech-api/v2/recognize?output=json&lang=it-IT&key=xxx';
$cont2 = array(
'flac/1.flac',
'flac/2.flac',
'flac/3.flac'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: audio/x-flac; rate=44100'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
foreach ($cont2 as $fn) {
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($fn));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
//var_dump($info);
if ($result === false) {
die(curl_error());
}else{
echo "<br />".$fn." upload ok"."<br />";
file_put_contents("pum.txt", $result, FILE_APPEND);
}
}
It works like a charm, in the "pum.txt" i have all the file content wrote and it's ok.
My problem is that i don't want to add to the the array "cont2", each time, the new name o the files i need to pass to, that there are in the "flac folder".
To avoid that, i use "scandir" method, remove "." and ".." string from the array and give that array to the CURL_OPT_POSTFIELD, but the call to GTT return a empty content.
This is the code i wrote to do that (instead $cont2 array)
$directory = 'flac/';
$cont = array_diff(scandir($directory), array('..', '.', '.DS_Store'));
Print_r of that is the same as $cont2 array:
array(3) {
[3]=>
string(6) "1.flac"
[4]=>
string(6) "2.flac"
[5]=>
string(6) "3.flac"
}
But Google TTS return empty result.
Does anyone please tell me where i'm making mistake?
Kind Regards
Brus
EDIT: use "$cont = glob("$directory/*.flac");" solved the issue. Hope help some others.
scandir() won't include full path information - it'll only return filenames. SO when you're building your array of filenames to loop on and send to google, you'll have to include that directories yourself.
e.g.
$dir = 'flac';
$files = scandir($dir);
foreach($files as $key => $file);
$files[$key] = $dir . '/' . $file;
}
e.g. scan dir will return file1.flac, but you need to have flac/file1.flac. Since you're not including the path information, you're trying to do file_get_contents() on a filename which doesn't exist, and are sending a boolean false (file_get failed) over to google.
As Marc B states you need the directory to the files which is missing. I would just use glob as it will return exactly what you need:
$cont = glob("$directory/*.flac");
Related
I am trying to implement a simple foldergrid php client. I am using the simple php client from the foldergrid api documentation. The client code that I got from the api documentation is:
class FolderGridClient {
protected $_cookieFileLocation = './cookie.txt';
public $_webpage;
public $_status;
public $_location;
const SERVER_HOST = 'https://secure.foldergrid.com';
public function authenticate($username,$password, $domain){
$params = array("domain"=>$domain,"username"=>$username,"password"=>$password);
$this->createCurl(self::SERVER_HOST."/login",$params);
}
public function createDomain($adminemail,$adminpassword, $domainname, $adminfname, $adminlname){
$json = json_encode( array('invite'=>true, 'admin' => array('email'=>$adminemail,'password'=>$adminpassword,'firstname'=>$adminfname,'lastname'=>$adminlname) ) );
$this->createCurl(self::SERVER_HOST."/domain/".$domainname,$json,true);
}
public function uploadFile($file,$name,$parentDuid) {
$fh = fopen($file, "rb");
if($fh) {
$json = json_encode( array('parentDuid'=>$parentDuid, 'name' => $name, 'parts' => 1) );
$this->createCurl(self::SERVER_HOST."/file/provision",$json,true);
if($this->_location){
$headers = array(
'fg-eap: false',
'fg-md5:'.md5_file($file),
'Content-Type: binary/octet-stream'
);
$curl = curl_init();
curl_setopt($curl,CURLOPT_PUT,true);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_URL, $this->_location);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curl, CURLOPT_INFILE, $fh);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($file));
curl_setopt( $curl, CURLOPT_VERBOSE, true );
$this->_webpage = curl_exec($curl);
$this->_status = curl_getinfo($curl,CURLINFO_HTTP_CODE);
fclose($fh);
curl_close($curl);
}
}else{
echo "File not found: $file \n";
}
}
public function fetchFolder($pathOrDuid){
$this->createCurl(self::SERVER_HOST."/folder/$pathOrDuid");
return $this->_webpage;
}
public function fetchFile($fileid){
$this->createCurl(self::SERVER_HOST."/file/$fileid");
return $this->_webpage;
}
public function createCurl($url,$postFields = null, $put = false)
{
$s = curl_init();
curl_setopt($s, CURLOPT_VERBOSE, true);
curl_setopt($s,CURLOPT_URL,$url);
curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
curl_setopt($s, CURLOPT_HEADER, TRUE);
curl_setopt($s,CURLOPT_FOLLOWLOCATION,false);
curl_setopt($s,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
curl_setopt($s,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);
if($postFields)
{
curl_setopt($s,CURLOPT_POST,true);
if($put) {
curl_setopt($s, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($postFields)));
curl_setopt($s,CURLOPT_CUSTOMREQUEST, "PUT");
}else{
curl_setopt($s, CURLOPT_HTTPHEADER, array('Expect:'));
}
curl_setopt($s,CURLOPT_POSTFIELDS,$postFields);
}
$this->_webpage = curl_exec($s);
$this->_status = curl_getinfo($s,CURLINFO_HTTP_CODE);
preg_match_all('/^Location:(.*)$/mi', $this->_webpage, $matches);
$this->_location = !empty($matches[1]) ? trim($matches[1][0]) : null;
curl_close($s);
}
}
Using this client, I was able to successfully upload a file to my folder grid root folder. Now I have created a test folder under the root, and I am trying to use the API to get the duid of the folder. I used the following code:
$uname='myuname';
$pwd='mypwd';
$domain='mydomain';
$rootDUID='duidOFRootFolder';
$client = new FolderGridClient;
$client->authenticate( $uname,$pwd,$domain);
if($client->_status < 400){
echo "fetchFolder: " . $client->fetchFolder($domain.'/TestNewFolder') . "<BR>";
}
TestNewFolder is the name of the folder I created using the foldergrid javascript reference client at https://mydomain.foldergrid.com/show/*.html
The root foldername is the same as my domain name, which i think is standard for foldergrid.
However, when I run that code, I always get a folder not found response. I have tried various different permutations of the folder path as an input to the fetchFolder function with no success. so two questions:
1. how should I use the fetchFolder function in the php simple client to get the folder info - specifically the duid.
2. Does anyone have an addition to the php simple client to create a sub folder, once I have discovered the duid of the target folder?
THANKS
When you create a new folder programmatically using the FolderGrid API you assign the immutable DUID which uniquely identifies that folder. One easy method to determine the DUID for any existing folder is to simply open the FolderGrid Web App and right click the folder to choose "Show Info".
To determine an unknown DUID programmatically using API calls, you simply traverse the folder path from a higher folder with a known DUID using calls to Show Folder Details which display the DUIDs of all subfolders. For example, you would execute a GET /folder/DUID on your root folder which will return (among other things) a json array of the names and DUIDs of all the subfolders of your root folder - including TestNewFolder
One useful shortcut is mentioned in the API docs for Show Folder Details which is that you can substitute asterisk '*' for DUID in that call as a shorthand reference to the root folder.
The sample PHP client code uses the name "pathOrDuid" for the parameter to fetchFolder but that's misleading because the call to retrieve a folder's details by path is a distinct call as documented here.
So following Simmerman's suggestions, here is some php code that I used to get the duid of a sub folder if I know the parent folders duid (like '*' for the root folder). I have added the following function to the php simple client that foldergrid provided in their documentation:
public function getSubFolderDuid($parentDuid,$folderName) {
$fetchParent = $this->fetchFolder($parentDuid);
$parentJsonMatch = array();
preg_match("/\{.*\}/",$fetchParent,&$parentJsonMatch);
$returnArray=true;
$parentJsonArray = json_decode($parentJsonMatch[0],$returnArray);
$subFolders = $parentJsonArray['folders'];
foreach($subFolders as $folderData) {
if ($folderData['name'] == $folderName) return $folderData['duid'];
}
return '';
}
obviously there is plenty of room to add error handling to this function in case the parent folder is not returned. This function is assuming the parent folder exists and is returned as json data.
Here is the code I used to call the function:
if($client->_status < 400){
$parentDuid = '*';
$folderName = 'TestNewFolder';
$folderDuid = $client->getSubFolderDuid($parentDuid,$folderName);
echo "$folderName: $folderDuid<br>";
}
With these building blocks I can now build code to traverse the directory tree or find a specific folder duid at an arbitrary depth in the tree.
Thanks for the pointing me in the right direction Simmerman
I am using the bukkit JSONAPI and php JSONAPI.php to get the list of players on my minecraft server to my website. To get the count, I do this:
require('JSONAPI.php'); // get this file at: https://github.com/alecgorge/jsonapi/raw/master/sdk/php/JSONAPI.php
$api = new JSONAPI("localhost", 20059, "user", "pass", "salt");
$limit = $api->call("getPlayerLimit");
$count = $api->call("getPlayerCount");
$c = curl_init($url);
curl_setopt($c, CURLOPT_PORT, 20059);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_TIMEOUT, 10);
$result = curl_exec($c);
curl_close($c);
echo "<h5>Players online:</h5>";
$num= '' . $count['success'] . '/' . $limit['success'];
echo $num;
This returns: 1/40
Then, I try to get the player list:
$list = $api->call('getPlayerNames');
echo $list;
This just returns: Array
However, when I do
var_dump($api->call('getPlayerNames'));
I get:
array(3) { ["result"]=> string(7) "success" ["source"]=> string(14) "getPlayerNames" ["success"]=> array(1) { [0]=> string(8) "gauso001" } }
However, what I want is simply a list of the players without all of the extra stuff. Sorry if this is a noob question, I only know pretty basic PHP.
Stuff that might help:
method docs: http://alecgorge.com/minecraft/jsonapi/apidocs/#package-JSONAPI%20standard
tell me what else..
THANK YOU in advance, I hope I'll be as good as you in PHP one day :D
Looks like player names, oddly enough, are contained as an array in the success key.
To access the player names, you could:
$list = $api->call('getPlayerNames');
// debug
print_r($list['success']);
// direct access
echo $list['success'][0];
// loop
foreach($list['success'] as $player) {
echo $player;
}
Format to your needs. But that should get you started.
Note: I'd also encourage you to learn about Arrays in PHP.
$api->call('getPlayerNames') returns a named array, one key of which (success) is another array containing the player names. Iterate over the success key to get the player list.
$players = $api->call('getPlayerNames');
foreach($players['success'] as $player) {
echo $player;
}
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.
I'm using cURL to transfer image files from one server to another using PHP. This is my cURL code:
// Transfer the original image and thumbnail to our storage server
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://' . $server_data['hostname'] . '.localhost/transfer.php');
curl_setopt($ch, CURLOPT_POST, true);
$post = array(
'upload[]' => '#' . $tmp_uploads . $filename,
'upload[]' => '#' . $tmp_uploads . $thumbname,
'salt' => 'q8;EmT(Vx*Aa`fkHX:up^WD^^b#<Lm:Q'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$resp = curl_exec($ch);
This is the code in transfer.php on the server I'm uploading to:
if($_FILES && $_POST['salt'] == 'q8;EmT(Vx*Aa`fkHX:up^WD^^b#<Lm:Q')
{
// Save the files
foreach($_FILES['upload']['error'] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
move_uploaded_file($_FILES['upload']['tmp_name'][$key], $_FILES['upload']['name'][$key]);
}
}
}
All seems to work, apart from one small logic error. Only one file is getting saved on the server I'm transferring to. This is probably because I'm calling both images upload[] in my post fields array, but I don't know how else to do it. I'm trying to mimic doing this:
<input type="file" name="upload[]" />
<input type="file" name="upload[]" />
Anyone know how I can get this to work? Thanks!
here is your error in the curl call...
var_dump($post)
you are clobbering the array entries of your $post array since the key strings are identical...
make this change
$post = array(
'upload[0]' => '#' . $tmp_uploads . $filename,
'upload[1]' => '#' . $tmp_uploads . $thumbname,
'salt' => 'q8;EmT(Vx*Aa`fkHX:up^WD^^b#<Lm:Q'
);
The code itself looks ok, but I don't know about your move() target directory. You're using the raw filename as provided by the client (which is your curl script). You're using the original uploaded filename (as specified in your curl script) as the target of the move, with no overwrite checking and no path data. If the two uploaded files have the same filename, you'll overwrite the first processed image with whichever one got processed second by PHP.
Try putting some debugging around the move() command:
if (!move_uploaded_file($_FILES['upload']['tmp_name'][$key], $_FILES['upload']['name'][$key])) {
echo "Unable to move $key/";
echo $_FILES['upload']['tmp_name'][$key];
echo ' to ';
echo $_FILES['upload']['name'][$key];
}
(I split the echo onto multiple lines for legibility).
I'm starting to help a friend who runs a website with small bits of coding work, and all the code required will be PHP. I am a C# developer, so this will be a new direction.
My first stand-alone task is as follows:
The website is informed of a new species of fish. The scientific name is entered into, say, two input controls, one for the genus (X) and another for the species (Y). These names will need to be sent to a website in the format:
http://www.fishbase.org/Summary/speciesSummary.php?genusname=X&speciesname=Y&lang=English
Once on the resulting page, there are further links for common names and synonyms.
What I would like to be able to do is to find these links, and call the URL (as this will contain all the necessary parameters to get the particular data) and store some of it.
I want to save data from both calls and, once completed, convert it all into xml which can then be uploaded to the website's database.
All I'd like to know is (a) can this be done, and (b) how difficult is it?
Thanks in advance
Martin
If I understand you correctly you want your script to download a page and process the downloaded data. If so, the answers are:
a) yes
b) not difficult
:)
Oke... here some more information: I would use the CURL extension, see:
http://php.net/manual/en/book.curl.php
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
?>
I used a thing called snoopy (http://sourceforge.net/projects/snoopy/) 4 years a go.
I took about 500 customers profiles from a website that published them in a few hours.
a) Yes
b) Not difficult when have experience.
Google for CURL first, or allow_url_fopen.
file_get_contents() will do the job:
$data = file_get_contents('http://www.fishbase.org/Summary/speciesSummary.php?genusname=X&speciesname=Y&lang=English');
// Отправить URL-адрес
function send_url($url, $type = false, $debug = false) { // $type = 'json' or 'xml'
$result = '';
if (function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
} else {
if (($content = #file_get_contents($url)) !== false) $result = $content;
}
if ($type == 'json') {
$result = json_decode($result, true);
} elseif ($type == 'xml') {
if (($xml = #simplexml_load_file($result)) !== false) $result = $xml;
}
if ($debug) echo '<pre>' . print_r($result, true) . '</pre>';
return $result;
}
$data = send_url('http://ip-api.com/json/212.76.17.140', 'json', true);