My goal is to create pages with information needed about the movie and with links that redirect to a video host where you will watch it. I found an IMDB php plugin and I am trying to insert in jquery mobile so mobile users will easily find the movies and stream them on their iDevices or any device that supports MP4 formats. Something close to http://freeflix.technoinsidr.com/watch.php?m=tt1190080
I've made this http://ivids.tk/test.php?m=tt0068646 How can I remove TITLE, YEAR (everything that's in BOLD) and put TITLE with the YEAR on the same line if its possible touse jquery mobile as the design? Is it even possible?
<?php
class Imdb
{
function getMovieInfo($title)
{
$imdbId = $this->getIMDbIdFromGoogle(trim($title));
if($imdbId === NULL){
$arr = array();
$arr['error'] = "No Title found in Search Results!";
return $arr;
}
return $this->getMovieInfoById($imdbId);
}
function getMovieInfoById($imdbId)
{
$arr = array();
$imdbUrl = "http://www.imdb.com/title/" . trim($imdbId) . "/";
$html = $this->geturl($imdbUrl);
if(stripos($html, "<meta name=\"application-name\" content=\"IMDb\" />") !== false){
$arr = $this->scrapMovieInfo($html);
$arr['imdb_url'] = $imdbUrl;
} else {
$arr['error'] = "No Title found on IMDb!";
}
return $arr;
}
function getIMDbIdFromGoogle($title){
$url = "http://www.google.com/search?q=imdb+" . rawurlencode($title);
$html = $this->geturl($url);
$ids = $this->match_all('/<a href="http:\/\/www.imdb.com\/title\/(tt\d+).*?".*?>.*?<\/a>/ms', $html, 1);
if (!isset($ids[0])) //if Google fails
return $this->getIMDbIdFromBing($title); //search using Bing
else
return $ids[0]; //return first IMDb result
}
function getIMDbIdFromBing($title){
$url = "http://www.bing.com/search?q=imdb+" . rawurlencode($title);
$html = $this->geturl($url);
$ids = $this->match_all('/<a href="http:\/\/www.imdb.com\/title\/(tt\d+).*?".*?>.*?<\/a>/ms', $html, 1);
if (!isset($ids[0]))
return NULL;
else
return $ids[0]; //return first IMDb result
}
// Scan movie meta data from IMDb page
function scrapMovieInfo($html)
{
$arr = array();
$arr['title'] = trim($this->match('/<title>(IMDb \- )*(.*?) \(.*?<\/title>/ms', $html, 2));
$arr['year'] = trim($this->match('/<title>.*?\(.*?(\d{4}).*?\).*?<\/title>/ms', $html, 1));
$arr['rating'] = $this->match('/ratingValue">(\d.\d)</ms', $html, 1);
$arr['genres'] = array();
foreach($this->match_all('/<a.*?>(.*?)<\/a>/ms', $this->match('/Genre.?:(.*?)(<\/div>|See more)/ms', $html, 1), 1) as $m)
array_push($arr['genres'], $m);
//Get extra inforation on Release Dates and AKA Titles
if($arr['title_id'] != ""){
$releaseinfoHtml = $this->geturl("http://www.imdb.com/title/" . $arr['title_id'] . "/releaseinfo");
$arr['also_known_as'] = $this->getAkaTitles($releaseinfoHtml, $usa_title);
$arr['usa_title'] = $usa_title;
$arr['release_date'] = $this->match('/Release Date:<\/h4>.*?([0-9][0-9]? (January|February|March|April|May|June|July|August|September|October|November|December) (19|20)[0-9][0-9]).*?(\(|<span)/ms', $html, 1);
$arr['release_dates'] = $this->getReleaseDates($releaseinfoHtml);
}
$arr['plot'] = trim(strip_tags($this->match('/<p itemprop="description">(.*?)(<\/p>|<a)/ms', $html, 1)));
$arr['poster'] = $this->match('/img_primary">.*?<img src="(.*?)".*?<\/td>/ms', $html, 1);
$arr['poster_small'] = "";
if ($arr['poster'] != '' && strrpos($arr['poster'], "nopicture") === false && strrpos($arr['poster'], "ad.doubleclick") === false) { //Get large and small posters
$arr['poster_small'] = preg_replace('/_V1\..*?.jpg/ms', "_V1._SY150.jpg", $arr['poster']);
} else {
$arr['poster'] = "";
}
$arr['runtime'] = trim($this->match('/Runtime:<\/h4>.*?(\d+) min.*?<\/div>/ms', $html, 1));
if($arr['runtime'] == '') $arr['runtime'] = trim($this->match('/infobar.*?(\d+) min.*?<\/div>/ms', $html, 1));
$arr['storyline'] = trim(strip_tags($this->match('/Storyline<\/h2>(.*?)(<em|<\/p>|<span)/ms', $html, 1)));
$arr['language'] = array();
foreach($this->match_all('/<a.*?>(.*?)<\/a>/ms', $this->match('/Language.?:(.*?)(<\/div>|>.?and )/ms', $html, 1), 1) as $m)
array_push($arr['language'], trim($m));
$arr['country'] = array();
foreach($this->match_all('/<a.*?>(.*?)<\/a>/ms', $this->match('/Country:(.*?)(<\/div>|>.?and )/ms', $html, 1), 1) as $c)
array_push($arr['country'], $c);
if($arr['title_id'] != "") $arr['media_images'] = $this->getMediaImages($arr['title_id']);
return $arr;
}
// Scan all Release Dates
function getReleaseDates($html){
$releaseDates = array();
foreach($this->match_all('/<tr>(.*?)<\/tr>/ms', $this->match('/Date<\/th><\/tr>(.*?)<\/table>/ms', $html, 1), 1) as $r)
{
$country = trim(strip_tags($this->match('/<td><b>(.*?)<\/b><\/td>/ms', $r, 1)));
$date = trim(strip_tags($this->match('/<td align="right">(.*?)<\/td>/ms', $r, 1)));
array_push($releaseDates, $country . " = " . $date);
}
return $releaseDates;
}
// Scan all AKA Titles
function getAkaTitles($html, &$usa_title){
$akaTitles = array();
foreach($this->match_all('/<tr>(.*?)<\/tr>/msi', $this->match('/Also Known As(.*?)<\/table>/ms', $html, 1), 1) as $m)
{
$akaTitleMatch = $this->match_all('/<td>(.*?)<\/td>/ms', $m, 1);
$akaTitle = trim($akaTitleMatch[0]);
$akaCountry = trim($akaTitleMatch[1]);
array_push($akaTitles, $akaTitle . " = " . $akaCountry);
if ($akaCountry != '' && strrpos(strtolower($akaCountry), "usa") !== false) $usa_title = $akaTitle;
}
return $akaTitles;
}
// Collect all Media Images
function getMediaImages($titleId){
$url = "http://www.imdb.com/title/" . $titleId . "/mediaindex";
$html = $this->geturl($url);
$media = array();
$media = array_merge($media, $this->scanMediaImages($html));
foreach($this->match_all('/<a href="\?page=(.*?)">/ms', $this->match('/<span style="padding: 0 1em;">(.*?)<\/span>/ms', $html, 1), 1) as $p)
{
$html = $this->geturl($url . "?page=" . $p);
$media = array_merge($media, $this->scanMediaImages($html));
}
return $media;
}
// Scan all media images
function scanMediaImages($html){
$pics = array();
foreach($this->match_all('/src="(.*?)"/ms', $this->match('/<div class="thumb_list" style="font-size: 0px;">(.*?)<\/div>/ms', $html, 1), 1) as $i)
{
array_push($pics, preg_replace('/_V1\..*?.jpg/ms', "_V1._SY0.jpg", $i));
}
return $pics;
}
// ************************[ Extra Functions ]******************************
function geturl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$ip=rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip"));
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/".rand(3,5).".".rand(0,3)." (Windows NT ".rand(3,5).".".rand(0,2)."; rv:2.0.1) Gecko/20100101 Firefox/".rand(3,5).".0.1");
$html = curl_exec($ch);
curl_close($ch);
return $html;
}
function match_all($regex, $str, $i = 0)
{
if(preg_match_all($regex, $str, $matches) === false)
return false;
else
return $matches[$i];
}
function match($regex, $str, $i = 0)
{
if(preg_match($regex, $str, $match) == 1)
return $match[$i];
else
return false;
}
}
?>
This really shouldn't be done in jQuery, and you could still use a few lessons in being clear with what you're looking for, but a question is a question, and here is my answer:
$('th').hide();
var $titlerow = $('tr td:first'),
$yearrow = $('tr:eq(1) td:first'),
title = $titlerow.text(),
year = $yearrow.text();
$titlerow.text(title + ' - ' + year);
$yearrow.remove();
Some things to note:
You should not be doing this is jQuery. You should rearrange your PHP. If the code is copy/pasted, then I suggest reading through it. I'll be honest, I didn't read a single line of what you posted, as it was irrelevant to a client-side question after you give a link.
You should be sure to include jQuery in your site. It is not on the page you linked to. Otherwise, the code I provided will not work.
You should put the above code in document ready. I left that last bit somewhat obfuscated. Reason being is that if you don't understand any of this bullet point, some googling of the terms in it will do you good.
Related
I'm getting the following error when trying to use Simple HTML Dom inside a web crawler class. The class seems to be working well but I get many errors in my error_log file.
[01-Apr-2016 23:16:51 UTC] PHP Warning: Invalid argument supplied for foreach() in /home/scrybs/public_html/order/uploader/php/simple_html_dom.php on line 357
If I check Simple HTML Dom, the error comes from here:
function innertext()
{
if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
$ret = '';
foreach ($this->nodes as $n)
$ret .= $n->outertext();
return $ret;
}
The crawler class in question is as following:
class crawler
{
protected $_url;
protected $_depth;
protected $_host;
protected $_useHttpAuth = false;
protected $_user;
protected $_pass;
protected $_seen = array();
protected $_filter = array();
public $contenu = array();
public function __construct($url, $depth = 5)
{
$this->_url = $url;
$this->_depth = $depth;
$parse = parse_url($url);
$this->_host = $parse['host'];
$this->html = new simple_html_dom();
}
protected function _processAnchors($content, $url, $depth)
{
//$dom = new DOMDocument('1.0');
//#$dom->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
//$dom->formatOutput = true;
$this->html->load($content);
$metatitle = $this->html->find('title',0)->innertext;
foreach($this->html->find("meta[name='description']") as $element){
$metadescription = $element->content;
}
foreach($this->html->find("meta[name='keywords']") as $element){
$metakeywords = $element->content;
}
if(!empty($metatitle)){
$this->contenu['meta_titles'][] = $metatitle;
}
if(!empty($metadescription)){
$this->contenu['meta_titles'][] = $metadescription;
}
if(!empty($metakeywords)){
$this->contenu['meta_titles'][] = $metakeywords;
}
// IMAGE ALTS
foreach($this->html->find('img') as $e){
if(!empty($e->alt)){
if(!$this->search_array($e->alt, $this->contenu)){
$this->contenu['alt_images'][] = $e->alt;
}
}
}
// LINKS
$links = $this->html->find('a');
foreach($links as $element){
// GET LINK TEXTS
$a = $element->innertext;
$a = preg_replace("/<a.*?>(.*?)<\/a>/", '\1', $a);
$a = preg_replace("/<p.*?>.*?<\/p>/", "{{P}}", $a);
$a = preg_replace("/<img.*?>/", "{{IMG}}", $a);
$a = preg_replace('#(<br */?>\s*)+#i', "{{BR}}", $a);
$a = preg_replace('#<button.*?>.*?</button>#i', '{{BUTTON}}', $a);
$a = preg_replace('#<time.*?>(.*?)</time>#i', '{{TIME}}', $a);
$a = preg_replace('#<span.*?>(.*?)</span>#i', '{{SPAN}}\1{{/SPAN}}', $a);
$a = preg_replace('#<strong.*?>(.*?)</strong>#i', '{{STRONG}}\1{{/STRONG}}', $a);
$a = preg_replace('#<b.*?>(.*?)</b>#i', '{{B}}\1{{/B}}', $a);
$a = preg_replace('#<i.*?>(.*?)</i>#i', '{{I}}\1{{/I}}', $a);
$a = preg_replace('#<small.*?>(.*?)</small>#i', '{{SMALL}}\1{{/SMALL}}', $a);
$a = preg_replace('#<abbr.*?>(.*?)</abbr>#i', '{{ABBR}}\1{{/ABBR}}', $a);
$a = trim(strip_tags($a));
$a = preg_replace('/\s+/', ' ', $a);
// CHECK IF NOT ONLY VARIABLES AND SPACES
$atmp = strip_tags($a);
$atmp = preg_replace("/{{.*?}}/", '', $atmp);
$atmp = preg_replace('/\s+/', '', $atmp);
if(!empty($a) && $a != '' && $atmp != ''){
if(!$this->search_array($a, $this->contenu)){
$this->contenu['link_texts'][] = $a;
}
}
// GET LINK TITLES
$title = $element->title;
if(!empty($title)){
if(!$this->search_array($title, $this->contenu)){
$this->contenu['link_titles'][] = $title;
}
}
$href = $element->href;
if (0 !== strpos($href, 'http')) {
$path = '/' . ltrim($href, '/');
if (extension_loaded('http')) {
$href = http_build_url($url, array('path' => $path));
} else {
$parts = parse_url($url);
$href = $parts['scheme'] . '://';
if (isset($parts['user']) && isset($parts['pass'])) {
$href .= $parts['user'] . ':' . $parts['pass'] . '#';
}
$href .= $parts['host'];
if (isset($parts['port'])) {
$href .= ':' . $parts['port'];
}
$href .= $path;
}
}
// Crawl only link that belongs to the start domain
$this->crawl_page($href, $depth - 1);
}
return $this->contenu;
}
protected function _getContent($url)
{
$handle = curl_init($url);
if ($this->_useHttpAuth) {
curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($handle, CURLOPT_USERPWD, $this->_user . ":" . $this->_pass);
}
// follows 302 redirect, creates problem wiht authentication
// curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);
// return the content
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
// response total time
$time = curl_getinfo($handle, CURLINFO_TOTAL_TIME);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
return array($response, $httpCode, $time);
}
protected function _printResult($url, $depth, $httpcode, $time)
{
ob_end_flush();
$currentDepth = $this->_depth - $depth;
$count = count($this->_seen);
//echo "N::$count,CODE::$httpcode,TIME::$time,DEPTH::$currentDepth URL::$url <br>";
ob_start();
flush();
}
protected function isValid($url, $depth)
{
if (strpos($url, $this->_host) === false
|| $depth === 0
|| isset($this->_seen[$url])
|| preg_match("/#/i", $url)
|| preg_match("/.png/i", $url)
|| preg_match("/.jpg/i", $url)
|| preg_match("/.jpeg/i", $url)
|| preg_match("/.gif/i", $url)
|| preg_match("/.pdf/i", $url)
|| preg_match("/javascript/i", $url)
|| preg_match("/twitter.com/i", $url)
|| preg_match("/google.com/i", $url)
|| preg_match("/facebook.com/i", $url)
|| preg_match("/youtube.com/i", $url)
|| preg_match("/instagram.com/i", $url)
|| preg_match("/wp-login.php/i", $url)
) {
return false;
}
foreach ($this->_filter as $excludePath) {
if (strpos($url, $excludePath) !== false) {
return false;
}
}
return true;
}
public function search_array($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && $this->search_array($needle, $element))
return true;
}
return false;
}
public function crawl_page($url, $depth)
{
if (!$this->isValid($url, $depth)) {
return;
}
// add to the seen URL
$this->_seen[$url] = true;
// get Content and Return Code
list($content, $httpcode, $time) = $this->_getContent($url);
// print Result for current Page
//$this->_printResult($url, $depth, $httpcode, $time);
// process subPages
$this->_processAnchors($content, $url, $depth, $contenu = array());
}
public function addFilterPath($path)
{
$this->_filter[] = $path;
}
public function run()
{
$this->crawl_page($this->_url, $this->_depth);
}
}
The error seems to be coming from this line related to innertext function:
// GET LINK TEXTS
$a = $element->innertext;
I don't get any error when I use:
$a = $element->innertext;
But not ideal as I would like to keep HTML tags. I don't get any error when I use Simple HTML Dom outside the class so does it have something to do with the fact that Simple HTML Dom is in a class? Do somebody have an idea?
Thanks for your help!
I have found the bug.
On my (limited) tests, the problem happens when you set depth > 1, so — seeing your code — when you load more than one page URL. One of the countless Simple HTML DOM problems, is that ->load() method doesn't work correctly on multiple loads.
Re-instantiating html object, the script seems work:
protected function _processAnchors( $content, $url, $depth )
{
$this->html = new simple_html_dom(); # <-----
$this->html->load( $content );
I tested also $this->html = str_get_html($content); but it works only on limited sites.
Additional Note: In HTML <title> tag is mandatory, but not all sites has well formatted HTML: consider checking for <title> tag (and for each tag) existence to avoid additional errors.
I am having a bit of trouble with some code where in an array I have a list of 2 and the function is only displaying the last in the list.
Here is the code:
<?php
function getKeywordPosition($theurl,$thekeywords) {
$theurl = $theurl;
$thekeywords = $thekeywords;
$found = false;
$x = 0;
for($x; $x < 64 && $found == false;)
{
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
. "q=".stripslashes(str_replace(' ', '%20', $thekeywords)).'&start='.$x;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.boo.com');
$body = curl_exec($ch);
curl_close($ch);
$json = json_decode($body);
$x4 = $x + 4;
$old_x = $x;
for($x; $x < $x4 && $found == false; $x = $x + 1)
{
if (strpos($json->responseData->results[$x-$old_x]->unescapedUrl, strtolower($theurl)) !== false)
{
$found = true;
}
}
// now have some fun with the results...
}
if($found)
{
echo '<strong>'.$theurl.'</strong> is located as the <strong>'.$x.'</strong> result when searching for <strong>'.stripslashes($thekeywords).'</strong>';
echo '<br>';
}
}
$list = array('php.com'=>'php', 'php.com'=>'php');
foreach($list as $key => $value){
getKeywordPosition($key,$value);
}
?>
Why is this not working properly?
Unless this is a badly contrived example, then th issue is you have duplicate keys in your array:
$list = array('php.com'=>'php', 'php.com'=>'php');
This array has a single entry
You coud refactor like so:
$list = array(
array('url'=>'php.net', 'keyword'=>'php'),
array('url'=>'php.net', 'keyword'=>'arrays'),
array('url'=>'php.net', 'keyword'=>'anotherkeyword')
);
foreach($list as $entry){
getKeywordPosition($entry['url'], $entry['keyword']);
}
I found a script which can extract the artist & title name from an Icecast or Shoutcast stream.
I want the script to update automatically when a song changed, at the moment its working only when i execute it. I'm new to PHP so any help will be appreciated.
Thanks!
define('CRLF', "\r\n");
class streaminfo{
public $valid = false;
public $useragent = 'Winamp 2.81';
protected $headers = array();
protected $metadata = array();
public function __construct($location){
$errno = $errstr = '';
$t = parse_url($location);
$sock = fsockopen($t['host'], $t['port'], $errno, $errstr, 5);
$path = isset($t['path'])?$t['path']:'/';
if ($sock){
$request = 'GET '.$path.' HTTP/1.0' . CRLF .
'Host: ' . $t['host'] . CRLF .
'Connection: Close' . CRLF .
'User-Agent: ' . $this->useragent . CRLF .
'Accept: */*' . CRLF .
'icy-metadata: 1'.CRLF.
'icy-prebuffer: 65536'.CRLF.
(isset($t['user'])?'Authorization: Basic '.base64_encode($t['user'].':'.$t['pass']).CRLF:'').
'X-TipOfTheDay: Winamp "Classic" rulez all of them.' . CRLF . CRLF;
if (fwrite($sock, $request)){
$theaders = $line = '';
while (!feof($sock)){
$line = fgets($sock, 4096);
if('' == trim($line)){
break;
}
$theaders .= $line;
}
$theaders = explode(CRLF, $theaders);
foreach ($theaders as $header){
$t = explode(':', $header);
if (isset($t[0]) && trim($t[0]) != ''){
$name = preg_replace('/[^a-z][^a-z0-9]*/i','', strtolower(trim($t[0])));
array_shift($t);
$value = trim(implode(':', $t));
if ($value != ''){
if (is_numeric($value)){
$this->headers[$name] = (int)$value;
}else{
$this->headers[$name] = $value;
}
}
}
}
if (!isset($this->headers['icymetaint'])){
$data = ''; $metainterval = 512;
while(!feof($sock)){
$data .= fgetc($sock);
if (strlen($data) >= $metainterval) break;
}
$this->print_data($data);
$matches = array();
preg_match_all('/([\x00-\xff]{2})\x0\x0([a-z]+)=/i', $data, $matches, PREG_OFFSET_CAPTURE);
preg_match_all('/([a-z]+)=([a-z0-9\(\)\[\]., ]+)/i', $data, $matches, PREG_SPLIT_NO_EMPTY);
echo '<pre>';var_dump($matches);echo '</pre>';
$title = $artist = '';
foreach ($matches[0] as $nr => $values){
$offset = $values[1];
$length = ord($values[0]{0}) +
(ord($values[0]{1}) * 256)+
(ord($values[0]{2}) * 256*256)+
(ord($values[0]{3}) * 256*256*256);
$info = substr($data, $offset + 4, $length);
$seperator = strpos($info, '=');
$this->metadata[substr($info, 0, $seperator)] = substr($info, $seperator + 1);
if (substr($info, 0, $seperator) == 'title') $title = substr($info, $seperator + 1);
if (substr($info, 0, $seperator) == 'artist') $artist = substr($info, $seperator + 1);
}
$this->metadata['streamtitle'] = $artist . ' - ' . $title;
}else{
$metainterval = $this->headers['icymetaint'];
$intervals = 0;
$metadata = '';
while(1){
$data = '';
while(!feof($sock)){
$data .= fgetc($sock);
if (strlen($data) >= $metainterval) break;
}
//$this->print_data($data);
$len = join(unpack('c', fgetc($sock))) * 16;
if ($len > 0){
$metadata = str_replace("\0", '', fread($sock, $len));
break;
}else{
$intervals++;
if ($intervals > 100) break;
}
}
$metarr = explode(';', $metadata);
foreach ($metarr as $meta){
$t = explode('=', $meta);
if (isset($t[0]) && trim($t[0]) != ''){
$name = preg_replace('/[^a-z][^a-z0-9]*/i','', strtolower(trim($t[0])));
array_shift($t);
$value = trim(implode('=', $t));
if (substr($value, 0, 1) == '"' || substr($value, 0, 1) == "'"){
$value = substr($value, 1);
}
if (substr($value, -1) == '"' || substr($value, -1) == "'"){
$value = substr($value, 0, -1);
}
if ($value != ''){
$this->metadata[$name] = $value;
}
}
}
}
fclose($sock);
$this->valid = true;
}else echo 'unable to write.';
}else echo 'no socket '.$errno.' - '.$errstr.'.';
}
public function print_data($data){
$data = str_split($data);
$c = 0;
$string = '';
echo "<pre>\n000000 ";
foreach ($data as $char){
$string .= addcslashes($char, "\n\r\0\t");
$hex = dechex(join(unpack('C', $char)));
if ($c % 4 == 0) echo ' ';
if ($c % (4*4) == 0 && $c != 0){
foreach (str_split($string) as $s){
//echo " $string\n";
if (ord($s) < 32 || ord($s) > 126){
echo '\\'.ord($s);
}else{
echo $s;
}
}
echo "\n";
$string = '';
echo str_pad($c, 6, '0', STR_PAD_LEFT).' ';
}
if (strlen($hex) < 1) $hex = '00';
if (strlen($hex) < 2) $hex = '0'.$hex;
echo $hex.' ';
$c++;
}
echo " $string\n</pre>";
}
public function __get($name){
if (isset($this->metadata[$name])){
return $this->metadata[$name];
}
if (isset($this->headers[$name])){
return $this->headers[$name];
}
return null;
}
}
$t = new streaminfo('http://64.236.34.196:80/stream/1014'); // get metadata
echo Meta Interval: $t->icymetaint;
echo Current Track: $t->streamtitle;
You will need to constantly query the stream at a set interval to find when the song changes.
This can be best done by scheduling a cron job.
If on Windows, you should use the Windows Task Scheduler
If you want to run the PHP script to keep your meta data up to date (I'm assuming you're making a website and using html audio tags here) you can use the ontimeupdate event with an ajax function. If you're not you probably should look up your audio playback documentation for something similar.
<audio src="http://ip:port/;" ontimeupdate="loadXMLDoc()">
You can find a great example here http://www.w3schools.com/php/php_ajax_php.asp
You want to use the PHP echo function all the relevant information at once using one php variable at the very end of your script.
<?php ....
$phpVar=$streamtitle;
$phpVar2=$streamsong;
$result="I want my string to look like this: <br> {$phpVar} {$phpVar2}";
echo $result;
?>
and then use the function called by the .onreadystatechange to modify the particular elements you want on your website by using the .resonseText (this will contain the same content as your PHP script's echo).
After SCOURING the web for 4 hours, this is the only Shoutcast metadata script I've found that works! Thankyou.
To run this constantly, why not use a setInterval combined with jQuery's AJAX call?
<script>
$(function() {
setInterval(getTrackName,16000);
});
function getTrackName() {
$.ajax({
url: "track_name.php"
})
.done(function( data ) {
$( "#results" ).text( data );
});
}
</script>
Also your last couple 'echo' lines were breaking the script for me. Just put quotes around the Meta Interval, etc....
I have sort of a "beginning" of a solution.
I wrote this function (Sorry about the spacings):
<?php
set_time_limit(0);
// Just to get the remote filesize
function checkFilesize($url, $user = "", $pw = ""){
ob_start();
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
if(!empty($user) && !empty($pw)){
$headers = array('Authorization: Basic ' . base64_encode("$user:$pw"));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$ok = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();
$regex = '/Content-Length:\s([0-9].+?)\s/';
$count = preg_match($regex, $head, $matches);
return isset($matches[1]) ? $matches[1] : "unknown";
}
// Split filesize to threads
function fileCutter($filesize,$threads){
$calc = round($filesize / count($threads));
$count = 0;
foreach($threads as $thread){
$rounds[$count] = $calc;
$count++;
}
$count = 0;
foreach($rounds as $round){
$set = $count + 1;
if($count == 0){
$from = 0;
} else {
$from = ($round * $count);
}
$cal = ($round * $set);
$final[$count] = array('from'=>$from,'to'=>$cal);
$count++;
}
// Correct the "Rounded" result
$end = end($final);
$differance = $filesize - $end['to'];
if (strpos($differance,'-') !== false) {} else {$add = '+';}
$end_result = ($end['to'].$add.$differance);
$value=eval("return ($end_result);");
$end_id = end(array_keys($final));
$final[$end_id]['to'] = $value;
// Return the complete array with the corrected result
return $final;
}
$threads = array(
0=>'test',
1=>'test',
2=>'test',
3=>'test',
4=>'test',
5=>'test',
);
$file = 'http://www.example.com/file.zip';
$filesize = checkFilesize($file);
$cuts = fileCutter($filesize,$threads);
print_r($cuts);
?>
(Again, Sorry. :) )
It gives "directions" to split the file in specific bytes.
I've tried to do something like so:
foreach($cuts as $cut){
$start = $cut['from'];
$finish = $cut['to'];
$f = fopen($file, "rb");
fseek($f, $start, SEEK_SET);
while(!(ftell($f) > $finish)){
$data = fgetc($f);
}
fclose($f);
But it's going to a endless loop.
What is the problem? or, is there another solution in PHP to split and combine files?
Instead of reading the file manually and byte-wise you could just use file_get_contents() with the according parameters $offset and $maxlen:
// $incp $ctx $offset $maxlen
$data = file_get_contents($fn, FALSE, NULL, $start, $finish-$start);
That'll do the seeking and cutting for you.
Right I have built a web crawler. It scans links, titles and meta descriptions. It scans the links and saves them in $link. It scans the titles of the links and saves them in [title] in newArray. Now in this array, I want to it to know that if there are no meta-tags, it can scan for the first p tag and use that instead. The only problem is that it doesn't seem to be saving any info at all.
function getMetas($link) {
$str1 = file_get_contents($link);
if (strlen($str1)>0) {
preg_match_all( '/<meta.*?name=("|\')description("|\').*?content=("|\')(.*?)("|\')/i', $str1, $description);
if (count($description) > 1) {
return $description[4];
}
}
return '';
if ($description == '') {
$html = file_get_contents($link);
preg_match('%(<p[^>]*>.*?</p>)%i', $html, $re);
$res = get_custom_excerpt($re[1]);
echo "\n";
echo $res;
echo "\n";
}
function get_custom_excerpt($return, $option = 30, $sentance = false) {
$marks = Array(".","!","?");
$return = strip_tags($return);
if($sentance == true) {
$start = implode(" ", array_slice(preg_split("/\s+/", $return), 0, $option ));
$start .= ' ';
$end = implode(" ", array_slice(preg_split("/\s+/", $return), $option));
$cut = Array();
foreach($marks AS $m => $mark){
$mark = strpos($end, $mark);
if($mark != false) $cut[$m] = $mark;
}
if($cut[0] != "")
$chop = min($cut);
else
$chop = $option;
$rest = substr($end, 0, $chop);
$key = array_search($chop, $cut);
$return = $start.$rest;
}else{
$return = implode(" ", array_slice(preg_split("/\s+/", $return), 0, $option));
}
$return .= $marks[$key];
return $return;
}
}
$output = Array();
foreach ($links as $thisLink) {
$output[] = array("link" => $thisLink, "title" => Titles($thisLink), "description" => getMetas($thisLink), getMetas($res));
}
print_r($output);
Your regex may not work. Attributes may not in your desired order.
it could be <meta name="" content=""> or <meta content="" name="">.
why don't you use an XML parser?
Most HTML is valid enough to be used for parsing.
Please have a look at PHP Parse HTML code