Get youtube title with php script - php

I would like to get the title of a youtube video in a variable, but everything I tried, didn't work. A part of the code below returns the title snippet in variable $output:
{ "items": [ { "snippet": {
"title": "Hardwell Live at Ultra Music Festival Miami 2016" } } ] }
But how could I get only the title in a variable?
<?php
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}
$response = curl_download('https://www.googleapis.com/youtube/v3/videos?id=m1ssAFzaCsU&key=AIzaSyBj5GoJlQ4XzebaG6H2tp_WVuQ03JEOOss&fields=items(snippet(title))&part=snippet');
if ($response) {
$xml = new SimpleXMLElement($response);
$title = (string) $xml->title;
echo $title;
} else {
// Error handling.
echo 'error';
}
?>

$output is a JSON string, use json_decode to parse it :
$output = '{ "items": [ { "snippet": { "title": "Hardwell Live at Ultra Music Festival Miami 2016" } } ] }';
$output_decoded = json_decode($output);
$title = $output_decoded->items[0]->snippet->title;
// $title is now 'Hardwell Live at Ultra Music Festival Miami 2016';
Adapted for your code :
<?php
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}
$response = curl_download('https://www.googleapis.com/youtube/v3/videos?id=m1ssAFzaCsU&key=AIzaSyBj5GoJlQ4XzebaG6H2tp_WVuQ03JEOOss&fields=items(snippet(title))&part=snippet');
if ($response) {
$response_decoded = json_decode($response);
$title = $response_decoded->items[0]->snippet->title;
echo $title;
} else {
// Error handling.
echo 'error';
}
?>

Related

PHP cURL lottery check page

I would like to have a lottery check page written in php. The code does not work with the Hungarian lottery database ($ url2) but works with the other ($ url1). Too much data is the problem?
<?php
echo "CURL - function test <br>";
$url1 = "http://www.example.com";
$url2 = "https://bet.szerencsejatek.hu/cmsfiles/otos.html";
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Set a referer
curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}
echo curl_download($url2);
echo strlen(curl_download($url2));
The first thing that it depends on what the error is.
I think you should dump the result of CURL work. Something like
if (!curl_errno($ch)) {
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case 200: # OK
$return = ['result' => 'ok', 'response_text' => $result];
break;
default:
$return = ['result' => 'unexpected_http_code', 'http_code' => $http_code,
'response_text' => $result
];
}
} else {
$return = ['result' => 'curl_error', 'curl_error' => curl_error($ch)];
}
Maybe it's because you didn't configure your SSL settings because the second URL starts with https://

How to get json data in below format

JSON Data :
{"FORM_ID":51393,
"ORG_ID":1527,
"REQUEST_ACTION":"ADD",
"ADD_DATA":
{
"RECORDS":
[
{
"ID":"0",
"COLUMNS":
[
{"NAME":"App Status", "VALUE":"Pending"},
{"NAME":"Remarks","VALUE":"Application in Pending"},
{"NAME":"App Date (dd/MMM/yyyy)" ,"VALUE":"2017-29-03 00:00:00.0"},
{"NAME":"Applicant First Name", "VALUE":"TEST WEBSERVICES First"},
{"NAME":"Applicant Middle Name", "VALUE":"TEST WEBSERVICES Second"},
{"NAME":"Applicant Last Name", "VALUE":"TEST WEBSERVICES Last"},
{"NAME":"Enquiry Center - Walk", "VALUE":"Telephonic"},
{"NAME":"Admission City Office", "VALUE":"TestCity"},
{"NAME":"Applicant Email Id", "VALUE":"test#test.com"},
{"NAME":"Nationality", "VALUE":"testNationality"},
{"NAME":"Country", "VALUE":"INDIA"},
{"NAME":"State", "VALUE":"MAHARASTRA"},
{"NAME":"City", "VALUE":"Mumbai"},
{"NAME":"Permanent Country", "VALUE":"INDIA"},
{"NAME":"Application Seq No", "VALUE":""}
{"NAME":"Application Seq No", "Mobile No":"9999999999"}
]
}
]
}
}
I don't know what are you try to do ,but if u have array
echo json_encode($array);
if u try to get it from url
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Set a referer
curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}
echo json_encode(curl_download("http://url.com")) ;

curl http code with redirections

I'm new with curl and I can't find my answer.
I want to get the http status of a page, so I'm using
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
But this does not work if there is a redirection (for example a 301 that redirect to another page, it will give me a 200 answer) because curlinfo_http_code gives the Last received HTTP code
Any idea how I can get the first received http code ?
thanks
You need to configure curl with CURLOPT_FOLLOWLOCATION = 0
The way I am accomplishing this is by having PHP consult an INI file with the different return codes and replacing them with something human readable
<?php
$ch = curl_init(); // create cURL handle (ch)
if (!$ch) {
die("Couldn't initialize a cURL handle");
}
// set some cURL options
$ret = curl_setopt($ch, CURLOPT_URL, "http://mail.yahoo.com");
$ret = curl_setopt($ch, CURLOPT_HEADER, 1);
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// execute
$ret = curl_exec($ch);
if (empty($ret)) {
// some kind of an error happened
die(curl_error($ch));
curl_close($ch); // close cURL handler
} else {
$info = curl_getinfo($ch);
curl_close($ch); // close cURL handler
if (empty($info['http_code'])) {
die("No HTTP code was returned");
} else {
// load the HTTP codes
$http_codes = parse_ini_file("HTMLCodes.ini");
// echo results
echo "The server responded: <br />";
echo $http_codes[$info['http_code']];
}
}
?>
example of the ini file with return codes
[Informational 1xx]
100="Continue"
101="Switching Protocols"
[Successful 2xx]
200="OK"
201="Created"
202="Accepted"
203="Non-Authoritative Information"
204="No Content"
205="Reset Content"
206="Partial Content"
[Redirection 3xx]
300="Multiple Choices"
301="Moved Permanently"
302="Found"
303="See Other"
304="Not Modified"
305="Use Proxy"
306="(Unused)"
307="Temporary Redirect"

PHP and ABBY recognition save to variable

i am using the ABBY API for OCR and i want to get the results in a variable for further processing instead of downloading the result as a file
<?php
include_once("dBug.php");
// Name of application you created
$applicationId = 'telianewtest';
// Password should be sent to your e-mail after application was created
$password = 'w0Ye61tWZ6fODm7hIUj9XTeJ';
$fileName = '20080118155747372_Page_2.jpg';
// Get path to file that we are going to recognize
$local_directory=dirname(__FILE__).'/images/';
$filePath = $local_directory.'/'.$fileName;
if(!file_exists($filePath))
{
die('File '.$filePath.' not found.');
}
if(!is_readable($filePath) )
{
die('Access to file '.$filePath.' denied.');
}
// Recognizing with English language to rtf
// You can use combination of languages like ?language=english,russian or
// ?language=english,french,dutch
// For details, see API reference for processImage method
$url = 'http://cloud.ocrsdk.com/processImage?language=english&exportFormat=xml';
// Send HTTP POST request and ret xml response
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandle, CURLOPT_USERPWD, "$applicationId:$password");
curl_setopt($curlHandle, CURLOPT_POST, 1);
curl_setopt($curlHandle, CURLOPT_USERAGENT, "PHP Cloud OCR SDK Sample");
$post_array = array(
"my_file"=>"#".$filePath,
);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $post_array);
$response = curl_exec($curlHandle);
if($response == FALSE) {
$errorText = curl_error($curlHandle);
curl_close($curlHandle);
die($errorText);
}
$httpCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle);
// Parse xml response
$xml = simplexml_load_string($response);
if($httpCode != 200) {
if(property_exists($xml, "message")) {
die($xml->message);
}
die("unexpected response ".$response);
}
$arr = $xml->task[0]->attributes();
$taskStatus = $arr["status"];
if($taskStatus != "Queued") {
die("Unexpected task status ".$taskStatus);
}
// Task id
$taskid = $arr["id"];
// 4. Get task information in a loop until task processing finishes
// 5. If response contains "Completed" staus - extract url with result
// 6. Download recognition result (text) and display it
$url = 'http://cloud.ocrsdk.com/getTaskStatus';
$qry_str = "?taskid=$taskid";
// Check task status in a loop until it is finished
// TODO: support states indicating error
while(true)
{
sleep(5);
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $url.$qry_str);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandle, CURLOPT_USERPWD, "$applicationId:$password");
curl_setopt($curlHandle, CURLOPT_USERAGENT, "PHP Cloud OCR SDK Sample");
$response = curl_exec($curlHandle);
$httpCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle);
// parse xml
$xml = simplexml_load_string($response);
if($httpCode != 200) {
if(property_exists($xml, "message")) {
die($xml->message);
}
die("Unexpected response ".$response);
}
$arr = $xml->task[0]->attributes();
$taskStatus = $arr["status"];
if($taskStatus == "Queued" || $taskStatus == "InProgress") {
// continue waiting
continue;
}
if($taskStatus == "Completed") {
// exit this loop and proceed to handling the result
break;
}
if($taskStatus == "ProcessingFailed") {
die("Task processing failed: ".$arr["error"]);
}
die("Unexpected task status ".$taskStatus);
}
// Result is ready. Download it
$url = $arr["resultUrl"];
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
// Warning! This is for easier out-of-the box usage of the sample only.
// The URL to the result has https:// prefix, so SSL is required to
// download from it. For whatever reason PHP runtime fails to perform
// a request unless SSL certificate verification is off.
curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curlHandle);
curl_close($curlHandle);
// Let user donwload rtf result
header('Content-type: application/txt');
header('Content-Disposition: attachment; filename="file.xml"');
echo $response;
?>
I tried to access the $xml variable with now success... any ideas?
Thank you in advance
(I have included the password since its a demo account, you can check it out if you want)

Trying to use curl to do a GET, value being sent is allows null

I'm trying to use curl to do a simple GET with one parameter called redirect_uri. The php file that gets called prints out a empty string for $_GET["redirect_uri"] it shows red= and it seems like nothing is being sent.
code to do the get
//Get code from login and display it
$ch = curl_init();
$url = 'http://www.besttechsolutions.biz/projects/facebook/testget.php';
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_GET,1);
curl_setopt($ch,CURLOPT_GETFIELDS,"redirect_uri=my return url");
//execute post
print "new reply 2 <br>";
$result = curl_exec($ch);
print $result;
// print "<br> <br>";
// print $fields_string;
die("hello");
the testget.php file
<?php
print "red-";
print $_GET["redirect_uri"];
?>
This is how I usually do get requests, hopefully it will help you:
// create curl resource
$ch = curl_init();
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Set maximum redirects
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
// Allow a max of 5 seconds.
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
// set url
if( count($params) > 0 ) {
$query = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, "$url?$query");
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
// $output contains the output string
$output = curl_exec($ch);
// Check for errors and such.
$info = curl_getinfo($ch);
$errno = curl_errno($ch);
if( $output === false || $errno != 0 ) {
// Do error checking
} else if($info['http_code'] != 200) {
// Got a non-200 error code.
// Do more error checking
}
// close curl resource to free up system resources
curl_close($ch);
return $output;
In this code, the $params could be an array where the key is the name, and the value is the value.

Categories