PHP Cron Job json_encode error - php

I have a PHP file that's running a simple check for currency conversion. It works perfectly when I run it through my browser but my goal is to build a cron. When I run the script via SSH:
php /path/to/file.php
I get the following:
PHP Warning: json_encode(): Invalid UTF-8 sequence in argument in /path/to/file.php on line 36
Where line 36 is:
fwrite($fh, json_encode($conversions));
...where $conversions is a simple single-dimension array
Here's the file:
$conversions = array();
$currencies = json_decode(file_get_contents("/path/to/currencies.json"), true);
foreach($currencies as $cur=>$data){
//make string to be put in API
$string = "1USD=?".$data['code'];
//Call Google API
$google_url = "http://www.google.com/ig/calculator?hl=en&q=".$string;
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $google_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// grab URL and pass it to the browser
$result = curl_exec($ch);
//Explode result to convert into an array
$result = explode('"', $result);
$converted_amount = explode(' ', $result[3]);
$conversion = $converted_amount[0];
//$conversion = $conversion * $amount;
$conversions[$cur] = $conversion;
if($conversion==0){ exit('0 Return Error'); }
curl_close($ch);
}
$fh = fopen("/path/to/currency_conversions.json", 'w') or die("can't open file");
fwrite($fh, json_encode($conversions));
fclose($fh);

Well, I searched for you and I found the json_encode acceptes only UTF-8
so here is the solution:
for($i=0;$i<count($conversions);$i++)
$conversions[$i] = utf8_encode($conversions[$i]);
fwrite($fh, json_encode($conversions));

Try updating your PHP version to a version later than version 5.2.7
Older version have UTF-8 bugs.

Related

How to use json to pass data from a php file to another php file

As mentioned earlier , i am working on the local server as of now in xampp. I have created 2 files index.php and test.php. What i want to achieve is that , index.php will send json data to test.php , with the json data received , the test.php is able to use that json data to turn the statistics into graph.
I am working with the first step , but however , nothing seems to display on my test.php when i tried to do a var_dump($data) , and what i get is NULL. Tried alot of solutions online but none to seems to fix it. I am relatively new to this , so really thanks and appreciate of your help. First php is index.php , second php is test.php.
Do i require a live server as of now in order to see the results in test.php or local server unable to display the result?
<?php
$array = array();
$product = array();
$product[0]['id_product'] = 'A01';
$product[0]['name_product'] = 'Sandal';
$product[0]['price_product'] = '500';
$product[1]['id_product'] = 'A02';
$product[1]['name_product'] = 'Shoes';
$product[1]['price_product'] = '2500';
$array['id'] = '123';
$array['note'] = 'this is my short example';
$array['data'] = $product;
$data = json_encode($array);
$ch = curl_init('http://localhost:8080/practice3/test.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($data));
$result = curl_exec($ch);
var_dump($result);
?>
```````````````````````````````````
<?php
$fp = fopen('php://input', 'r');
$raw = stream_get_contents($fp);
$data = json_decode($raw,true);
echo "hello";
echo $data['id'];
echo $data['note'];
foreach ($data['data'] as $key) {
echo 'id_product : '.$key['id_product'].'<br/>';
echo 'name_product : '.$key['name_product'].'<br/>';
echo 'price_product : '.$key['price_product'].'<br/>';
}
?>
````````````````````````````````````

Get location from a stream url in PHP

I'm trying to get the redirect url from a stream using php.
Here's the code I have right now:
<?php
$stream = 'https://api.soundcloud.com/tracks/178525956/stream?client_id=XXXXXX';
$ch = curl_init($stream);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$url = curl_exec($ch);
echo $url;
curl_close($ch);
?>
Which outputs as a string:
{"status":"302 - Found","location":"THE_URL_I_WANT"}
So how ould I go about getting the url I want as a variable?
Thanks
It's simple use json_decode
$data = json_decode($url);
$your_url = $data->location;
How about
$data = json_decode($url);
$location = $data["location"];

PHP Get metadata of remote .mp3 file (from URL)

I am trying to get song name / artist name / song length / bitrate etc from a remote .mp3 file such as http://shiro-desu.com/scr/11.mp3 .
I have tried getID3 script but from what i understand it doesn't work for remote files as i got this error: "Remote files are not supported - please copy the file locally first"
Also, this code:
<?php
$tag = id3_get_tag( "http://shiro-desu.com/scr/11.mp3" );
print_r($tag);
?>
did not work either.
"Fatal error: Call to undefined function id3_get_tag() in /home4/shiro/public_html/scr/index.php on line 2"
As you haven't mentioned your error I am considering a common error case undefined function
The error you get (undefined function) means the ID3 extension is not enabled in your PHP configuration:
If you dont have Id3 extension file .Just check here for installation info.
Firstly, I didn’t create this, I’ve just making it easy to understand with a full example.
You can read more of it here, but only because of archive.org.
https://web.archive.org/web/20160106095540/http://designaeon.com/2012/07/read-mp3-tags-without-downloading-it/
To begin, download this library from here: http://getid3.sourceforge.net/
When you open the zip folder, you’ll see ‘getid3’. Save that folder in to your working folder.
Next, create a folder called “temp” in that working folder that the following script is going to be running from.
Basically, what it does is download the first 64k of the file, and then read the metadata from the file.
I enjoy a simple example. I hope this helps.
<?php
require_once("getid3/getid3.php");
$url_media = "http://example.com/myfile.mp3"
$a=getfileinfo($url_media);
echo"<pre>";
echo $a['tags']['id3v2']['album'][0] . "\n";
echo $a['tags']['id3v2']['artist'][0] . "\n";
echo $a['tags']['id3v2']['title'][0] . "\n";
echo $a['tags']['id3v2']['year'][0] . "\n";
echo $a['tags']['id3v2']['year'][0] . "\n";
echo "\n-----------------\n";
//print_r($a['tags']['id3v2']['album']);
echo "-----------------\n";
//print_r($a);
echo"</pre>";
function getfileinfo($remoteFile)
{
$url=$remoteFile;
$uuid=uniqid("designaeon_", true);
$file="temp/".$uuid.".mp3";
$size=0;
$ch = curl_init($remoteFile);
//==============================Get Size==========================//
$contentLength = 'unknown';
$ch1 = curl_init($remoteFile);
curl_setopt($ch1, CURLOPT_NOBODY, true);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HEADER, true);
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
$data = curl_exec($ch1);
curl_close($ch1);
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
$size=$contentLength;
}
//==============================Get Size==========================//
if (!$fp = fopen($file, "wb")) {
echo 'Error opening temp file for binary writing';
return false;
} else if (!$urlp = fopen($url, "r")) {
echo 'Error opening URL for reading';
return false;
}
try {
$to_get = 65536; // 64 KB
$chunk_size = 4096; // Haven't bothered to tune this, maybe other values would work better??
$got = 0; $data = null;
// Grab the first 64 KB of the file
while(!feof($urlp) && $got < $to_get) { $data = $data . fgets($urlp, $chunk_size); $got += $chunk_size; } fwrite($fp, $data); // Grab the last 64 KB of the file, if we know how big it is.
if ($size > 0) {
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RESUME_FROM, $size - $to_get);
curl_exec($ch);
}
// Now $fp should be the first and last 64KB of the file!!
#fclose($fp);
#fclose($urlp);
}
catch (Exception $e) {
#fclose($fp);
#fclose($urlp);
echo 'Error transfering file using fopen and cURL !!';
return false;
}
$getID3 = new getID3;
$filename=$file;
$ThisFileInfo = $getID3->analyze($filename);
getid3_lib::CopyTagsToComments($ThisFileInfo);
unlink($file);
return $ThisFileInfo;
}
?>

How get content from specific link?

I have link in specific variable eg.
$link = 'http://google.com'
and I try to get content from this link with function fopen.
Eg. : $var = fopen("'".$link."'", "rb");
echo stream_get_contents($var); ,
but without success. Error is
Warning: file_get_contents('http://google.com'): failed to open stream: No such file or directory in /var/www/...
If I use directly
$var = fopen('http://google.com', "rb");
echo stream_get_contents($var)
this work perfectly?
How do I fix this or what method to use if I link is a variable?
Based on your posted code, this worked for me. Try it using this method:
<?php
$link = "http://www.google.com";
$var = fopen($link, "rb");
echo stream_get_contents($var)
?>
This always worked for me.
$url = 'http://google.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);

Error in Getting Youtube Video Title, Description and thumbnail

I was getting youtube title and youtube description form the same code but now its not working
I am getting following error:
Warning: DOMDocument::load() [domdocument.load]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/colorsfo/public_html/zaroorat/admin/pages/addSongProcess.php on line 16
Warning: DOMDocument::load(http://gdata.youtube.com/feeds/api/videos/Y7G-tYRzwYY) [domdocument.load]: failed to open stream: no suitable wrapper could be found in /home/colorsfo/public_html/zaroorat/admin/pages/addSongProcess.php on line 16
Warning: DOMDocument::load() [domdocument.load]: I/O warning : failed to load external entity "http://gdata.youtube.com/feeds/api/videos/Y7G-tYRzwYY" in /home/colorsfo/public_html/zaroorat/admin/pages/addSongProcess.php on line 16
....................................
Following Coding is used to get Youtube Video Data:
$url = "http://gdata.youtube.com/feeds/api/videos/".$embedCodeParts2[0];
$doc = new DOMDocument;
#$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
$videoDescription = $doc->getElementsByTagName("description")->item(0)->nodeValue;
It was working before (This coding is working fine in Local server but on internet its not working) but now its not working. Please guide me how to fix this error.
Thanks for your time.
Your server's allow_url_fopen is disabled (so is mine). I feel your pain. Here's what I did.
Try using cURL, but return your data in json, using YouTube's v2 api. You do that by appending that data to the end of your url.
?v=2&alt=json
You didn't post how you're getting your YouTube ID, and that may be a part of the issue (though your sample url did work). So just in case, I'm also posting a simple function to retrieve the ID from the YouTube video url.
function get_youtube_id($url) {
$newurl = parse_url($url);
return substr($newurl['query'],2);
}
OK, now assuming you have your video id, you can run the following function for each field you wish to return.
// Grab JSON and format it into PHP arrays from YouTube.
// Options defined in the switch. No option returns entire array
// Example of what the returned JSON will look like, pretty, here:
// http://gdata.youtube.com/feeds/api/videos/dQw4w9WgXcQ?v=2&alt=json&prettyprint=true
function get_youtube_info ( $vid, $info ) {
$youtube = "http://gdata.youtube.com/feeds/api/videos/$vid?v=2&alt=json";
$ch = curl_init($youtube);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
//If $assoc = true doesn't work, try:
//$output = json_decode($output, true);
$output = json_decode($output, $assoc = true);
//Add the ['feed'] in if it exists.
if ($output['feed']) {
$path = &$output['feed']['entry'];
} else {
$path = &$output['entry'];
}
//set up a switch to return various data bits to return.
switch($info) {
case 'title':
$output = $path['title']['$t'];
break;
case 'description':
$output = $path['media$group']['media$description']['$t'];
break;
case 'author':
$output = $path['author'][0]['name'];
break;
case 'author_uri':
$output = $path['author'][0]['uri'];
break;
case 'thumbnail_small':
$output = $path['media$group']['media$thumbnail'][0]['url'];
break;
case 'thumbnail_medium':
$output = $path['media$group']['media$thumbnail'][2]['url'];
break;
case 'thumbnail_large':
$output = $path['media$group']['media$thumbnail'][3]['url'];
break;
default:
return $output;
break;
}
return $output;
}
$url = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$id = get_youtube_id($url);
echo "<h3>" . get_youtube_info($id, 'title') . "</h3>"; //echoes the title
echo "<p><img style='float:left;margin-right: 5px;' src=" . get_youtube_info($id, 'thumbnail_small') . " />" . get_youtube_info($id, 'description') . "</p>"; //echoes the description
echo "<br style='clear:both;' /><pre>";
echo print_r(get_youtube_info($id));
echo "</pre>";
DOMDocuments' load() function uses PHPs fopen wrappers to retrieve files.
It seems that on your webserver, allow_url_fopen is set to 0, thus disabling these wrappers.
Try adding the following line to the top of your script:
ini_set ('allow_url_fopen', 1);
UPDATE: Try this:
<?php
$url = "http://gdata.youtube.com/feeds/api/videos/" . $embedCodeParts2[0];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$file = curl_exec($ch);
curl_close($ch);
$doc = new DOMDocument;
#$doc->loadHTML($file);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
$videoDescription = $doc->getElementsByTagName("description")->item(0)->nodeValue;
I hope it is not too late. My solution is to edit /etc/resolv.conf in your Linux machine: and replace first line with below line:
nameserver 8.8.8.8
Then save the file. no need for service restart.
Might work for servers who disabled some function accidentally for security.

Categories