I have been using the Yahoo Financial API to download historical stock data from Yahoo. As has been reported on this site, as of mid May, the old API was discontinued. There have been many posts addressed the the form of the new call, e.g.:
https://query1.finance.yahoo.com/v7/finance/download/AAPL?period1=315561600&period2=1496087439&interval=1d&events=history&crumb=XXXXXXXXXXX
As well as methods for obtaining the crumb:
Yahoo Finance URL not working
But I must be misunderstanding what the procedure is as I always get an error saying that it "Failed to open stream: HTTP request failed. HTTP/1.0 201 Unauthorized".
Below is my code. Any and all assistance is welcome. I have to admit that I am an old Fortran programmer and my coding reflects this.
Good Roads
Bill
$ticker = "AAPL";
$yahooURL="https://finance.yahoo.com/quote/" .$ticker ."/history";
$body=file_get_contents($yahooURL);
$headers=$http_response_header;
$icount = count($headers);
for($i = 0; $i < $icount; $i ++)
{
$istart = -1;
$istop = -1;
$istart = strpos($headers[$i], "Set-Cookie: B=");
$istop = strpos($headers[$i], "&b=");
if($istart > -1 && $istop > -1)
{
$Cookie = substr ( $headers[$i] ,$istart+14,$istop - ($istart + 14));
}
}
$istart = strpos($body,"CrumbStore") + 22;
$istop = strpos($body,'"', $istart);
$Crumb = substr ( $body ,$istart,$istop - $istart);
$iMonth = 1;
$iDay = 1;
$iYear = 1980;
$timestampStart = mktime(0,0,0,$iMonth,$iDay,$iYear);
$timestampEnd = time();
$url = "https://query1.finance.yahoo.com/v7/finance/download/".$ticker."?period1=".$timestampStart."&period2=".$timestampEnd."&interval=1d&events=history&crumb=".$Cookie."";
while (!copy($url, $newfile) && $iLoop < 10)
{
if($iLoop == 9) echo "Failed to download data." .$lf;
$iLoop = $iLoop + 1;
sleep(1);
}
#Craig Cocca this isn't exactly a duplicate because the reference you gave gives a solution in python which for those of us who use php but haven't learnt python doesn't help much. I'd love to see as solution with php. I've examinied the yahoo page and am able to extract the crumb but can't work out how to put it into a stream and GET call.
My latest (failed) effort is:
$headers = [
"Accept" => "*/*",
"Connection" => "Keep-Alive",
"User-Agent" => sprintf("curl/%s", curl_version()["version"])
];
// open connection to Yahoo
$context = stream_context_create([
"http" => [
"header" => (implode(array_map(function($value, $key) { return sprintf("%s: %s\r\n", $key, $value); }, $headers, array_keys($headers))))."Cookie: $Cookie",
"method" => "GET"
]
]);
$handle = #fopen("https://query1.finance.yahoo.com/v7/finance/download/{$symbol}?period1={$date_now}&period2={$date_now}&interval=1d&events=history&crumb={$Crumb}", "r", false, $context);
if ($handle === false)
{
// trigger (big, orange) error
trigger_error("Could not connect to Yahoo!", E_USER_ERROR);
exit;
}
// download first line of CSV file
$data = fgetcsv($handle);
The two dates are unix coded dates i.e.: $date_now = strtotime($date);
I've now managed to download share price history. At the moment I'm only taking the current price figures but my download method receives historical data for the past year. (i.e. until Yahoo decides to put some other block on the data).
My solution uses the "simple_html_dom.php" parser which I've added to my /includes folder.
Here is the code (modified from the original version from the Harvard CS50 course which I recommend for beginners like me):
function lookup($symbol)
{
// reject symbols that start with ^
if (preg_match("/^\^/", $symbol))
{
return false;
}
// reject symbols that contain commas
if (preg_match("/,/", $symbol))
{
return false;
}
// body of price history search
$sym = $symbol;
$yahooURL='https://finance.yahoo.com/quote/'.$sym.'/history?p='.$sym;
// get stock name
$data = file_get_contents($yahooURL);
$title = preg_match('/<title[^>]*>(.*?)<\/title>/ims', $data, $matches) ? $matches[1] : null;
$title = preg_replace('/[[a-zA-Z0-9\. \| ]* \| /','',$title);
$title = preg_replace('/ Stock \- Yahoo Finance/','',$title);
$name = $title;
// get price data - use simple_html_dom.php (added to /include)
$body=file_get_html($yahooURL);
$tables = $body->find('table');
$dom = new DOMDocument();
$elements[] = null;
$dom->loadHtml($tables[1]);
$x = new DOMXpath($dom);
$i = 0;
foreach($x->query('//td') as $td){
$elements[$i] = $td -> textContent." ";
$i++;
}
$open = floatval($elements[1]);
$high = floatval($elements[2]);
$low = floatval($elements[3]);
$close = floatval($elements[5]);
$vol = str_replace( ',', '', $elements[6]);
$vol = floatval($vol);
$date = date('Y-m-d');
$datestamp = strtotime($date);
$date = date('Y-m-d',$datestamp);
// return stock as an associative array
return [
"symbol" => $symbol,
"name" => $name,
"price" => $close,
"open" => $open,
"high" => $high,
"low" => $low,
"vol" => $vol,
"date" => $date
];
}
Related
I am trying to create a try/catch loop that I am using for downloading HTML from another website:
foreach($intldes as $id) {
$html = HtmlDomParser::file_get_html('https://nssdc.gsfc.nasa.gov/nmc/spacecraftDisplay.do?id='.$id);
foreach($html->find('#rightcontent') as $id);
foreach($html->find('.urone p') as $element);
foreach($html->find('.urtwo') as $launchdata);
}
If the data exists, it results in the following HTML:
<p><strong>NSSDCA/COSPAR ID:</strong> 2009-038F</p>
<p>ANDE 2, the Atmospheric Neutral Density Experiment 2, is a pair of microsatellites (Castor and Pollux) launched from Cape Canaveral on STS 127 on 15 July 2009 at 22:03 UT and deployed from the payload bay of the shuttle on 30 July 2009 at 17:22 UT.</p>
<p><strong>Launch Date:</strong> 2009-07-15<br/><strong>Launch Vehicle:</strong> Shuttle<br/><strong>Launch Site:</strong> Cape Canaveral, United States<br/></p>
If the data does not exist, I get a Undefined variable: element error, which means that the DOM Parser could not find the HTML that I want to display.
So I need a something that skips the webpages that do not have the required HTML or a variable of NULL returned.
Basically, if the HTML I want or the variable $element does not exist, I want Guzzle to skip that webpage and not load it.
EDIT:
My full function:
public function tester() {
$intldes = DB::table('examples')->pluck('id');
foreach ($intldes as $query) {
$html = HtmlDomParser::file_get_html('https://example.com?id='.$query);
$elements = $html->find('.urone p', 0);
if (is_array($elements)) {
foreach($html->find('#rightcontent') as $rawid);
foreach($html->find('.urone p') as $rawdescription);
foreach($html->find('.urtwo') as $launchdata);
//-- Data Parser --//
//Intldes
$intldesgetter = strip_tags($rawid->first_child()->next_sibling()->next_sibling()); //Get Element and Remove Tags
$intldesformat = substr($intldesgetter, ($pos = strpos($intldesgetter, ':')) !== false ? $pos + 3 : 0); //Remove Title
$dbintldes = ltrim($intldesformat); //Remove Blank-space
//Description
$description = strip_tags($rawdescription);
$dbdescription = ltrim($description);
//Launch Data
$launchdate = $launchdata->first_child()->next_sibling()->next_sibling()->next_sibling();
$explode = explode("<br/>", $launchdate);
$newArray = array_map(function($v){
return trim(strip_tags($v));
}, $explode);
$dblaunchdate = substr($newArray[0], ($pos = strpos($newArray[0], ':')) !== false ? $pos + 3 : 0);
$dblaunchvehicle = substr($newArray[1], ($pos = strpos($newArray[1], ':')) !== false ? $pos + 3 : 0);
$dblaunchsite = substr($newArray[2], ($pos = strpos($newArray[2], ':')) !== false ? $pos + 3 : 0);
//Data Saver
DB::table('descriptions')->insert(
['intldes' => $dbintldes, 'description' => strip_tags($dbdescription), 'launch_date' => $dblaunchdate, 'launch_vehicle' => $dblaunchvehicle, 'launch_site' => $dblaunchsite]
);
echo "Success";
} else {
echo "$query does not exist";
continue;
};
}
}
I think you are getting error here in your code:
foreach($html->find('.urone p') as $element);
From my experience, I would recommend to you that you should check for the availability of the HTML tag first before iterating in the foreach loop.
You can use either is_object() or is_array() to get work around your problem. When you search for a single element, an object is returned. When you search for a set of elements, an array of objects is returned.
As you are searching for set of elements then you can use
$elements = $html->find('.urone p');
if (is_array($elements)) {
//continue
}
I am trying to split up a string to stay under the limit of 70 characters... however, when i do this, my loop just stop right when it gets the first 70 characters and it doesn't attempt to do the 2nd set. The reason I'm going this route and not use str_split is to keep the entire words so I don't send out messages with half of a word. If the 2nd split has less than 70 characters, please still send it out...any kind of help with this is greatly appreciated.
$message="A new powerful earthquake convulsed the traumatized nation of Nepal on Tuesday, leveling buildings already damaged by the devastating quake that killed thousands of people less than three weeks ago."
$msg = explode(' ',$message);
foreach($msg as $key) {
$keylen = strlen($key);
$msglen = $msglen + $keylen;
if($msglen<70) {
$msgs .=$key." ";
// $agi->verbose("$msgs");
} else {
$params = array(
'src' => '18009993355',
'dst' => $callerid,
'text' => $msgs,
'type' => 'sms',
);
// $agi->verbose("sending: $msgs");
$response = $p->send_message($params);
$msgs = "";
$msglen = 0;
}
}
<?php
$message = "A new powerful earthquake convulsed the traumatized nation of Nepal on Tuesday, leveling buildings already damaged by the devastating quake that killed thousands of people less than three weeks ago.";
define ("MAX_PACKET_SIZE", 70);
$msg = explode (' ',$message);
$indexes = array (0);
$actualSize = 0 ;
for ($i=0 ; $i<count($msg) ; $i++) {
if ($actualSize + strlen ($msg[$i]) <= MAX_PACKET_SIZE ) {
$actualSize += strlen ($msg[$i]);
if (($i+1) < count($msg)) {
$actualSize++;
}
}else {
$indexes[] = $i;
$actualSize = 0 ;
}
}
$indexes[] = count ($msg);
for ($i=1 ; $i<count($indexes) ; $i++) {
$temp = array_extract ($msg, $indexes[$i-1], $indexes[$i]);
var_dump(implode (' ', $temp));
$params = array ('src' => '18009993355',
'dst' => $callerid,
'text' => implode (' ', $temp) ,
'type' => 'sms');
// $agi->verbose("sending: $msgs");
$response = $p->send_message($params);
}
function array_extract ($array, $start, $stop) {
$temp = array();
for ($i=$start ; $i<$stop ; $i++) {
$temp[] = $array[$i];
}
return $temp;
}
What does $msg contain? If the first message contains 49 or less characters, whilst the second message contains another 50 characters, it will not send the second message, isn't that the point?
You could place some var_dumps here and there to debug it.
I want to parse shortcode like Wordpress with attributes:
Input:
[include file="header.html"]
I need output as array, function name "include" and attributes with values as well , any help will be appreciated.
Thanks
Here's a utility class that we used on our project
It will match all shortcodes in a string (including html) and it will output an associative array including their name, attributes and content
final class Parser {
// Regex101 reference: https://regex101.com/r/pJ7lO1
const SHORTOCODE_REGEXP = "/(?P<shortcode>(?:(?:\\s?\\[))(?P<name>[\\w\\-]{3,})(?:\\s(?P<attrs>[\\w\\d,\\s=\\\"\\'\\-\\+\\#\\%\\!\\~\\`\\&\\.\\s\\:\\/\\?\\|]+))?(?:\\])(?:(?P<content>[\\w\\d\\,\\!\\#\\#\\$\\%\\^\\&\\*\\(\\\\)\\s\\=\\\"\\'\\-\\+\\&\\.\\s\\:\\/\\?\\|\\<\\>]+)(?:\\[\\/[\\w\\-\\_]+\\]))?)/u";
// Regex101 reference: https://regex101.com/r/sZ7wP0
const ATTRIBUTE_REGEXP = "/(?<name>\\S+)=[\"']?(?P<value>(?:.(?![\"']?\\s+(?:\\S+)=|[>\"']))+.)[\"']?/u";
public static function parse_shortcodes($text) {
preg_match_all(self::SHORTOCODE_REGEXP, $text, $matches, PREG_SET_ORDER);
$shortcodes = array();
foreach ($matches as $i => $value) {
$shortcodes[$i]['shortcode'] = $value['shortcode'];
$shortcodes[$i]['name'] = $value['name'];
if (isset($value['attrs'])) {
$attrs = self::parse_attrs($value['attrs']);
$shortcodes[$i]['attrs'] = $attrs;
}
if (isset($value['content'])) {
$shortcodes[$i]['content'] = $value['content'];
}
}
return $shortcodes;
}
private static function parse_attrs($attrs) {
preg_match_all(self::ATTRIBUTE_REGEXP, $attrs, $matches, PREG_SET_ORDER);
$attributes = array();
foreach ($matches as $i => $value) {
$key = $value['name'];
$attributes[$i][$key] = $value['value'];
}
return $attributes;
}
}
print_r(Parser::parse_shortcodes('[include file="header.html"]'));
Output:
Array
(
[0] => Array
(
[shortcode] => [include file="header.html"]
[name] => include
[attrs] => Array
(
[0] => Array
(
[file] => header.html
)
)
)
)
Using this function
$code = '[include file="header.html"]';
$innerCode = GetBetween($code, '[', ']');
$innerCodeParts = explode(' ', $innerCode);
$command = $innerCodeParts[0];
$attributeAndValue = $innerCodeParts[1];
$attributeParts = explode('=', $attributeAndValue);
$attribute = $attributeParts[0];
$attributeValue = str_replace('"', '', $attributeParts[1]);
echo $command . ' ' . $attribute . '=' . $attributeValue;
//this will result in include file=header.html
$command will be "include"
$attribute will be "file"
$attributeValue will be "header.html"
I also needed this functionality in my PHP framework. This is what I've written, it works pretty well. It works with anonymous functions, which I really like (it's a bit like the callback functions in JavaScript).
<?php
//The content which should be parsed
$content = '<p>Hello, my name is John an my age is [calc-age day="4" month="10" year="1991"].</p>';
$content .= '<p>Hello, my name is Carol an my age is [calc-age day="26" month="11" year="1996"].</p>';
//The array with all the shortcode handlers. This is just a regular associative array with anonymous functions as values. A very cool new feature in PHP, just like callbacks in JavaScript or delegates in C#.
$shortcodes = array(
"calc-age" => function($data){
$content = "";
//Calculate the age
if(isset($data["day"], $data["month"], $data["year"])){
$age = date("Y") - $data["year"];
if(date("m") < $data["month"]){
$age--;
}
if(date("m") == $data["month"] && date("d") < $data["day"]){
$age--;
}
$content = $age;
}
return $content;
}
);
//http://stackoverflow.com/questions/18196159/regex-extract-variables-from-shortcode
function handleShortcodes($content, $shortcodes){
//Loop through all shortcodes
foreach($shortcodes as $key => $function){
$dat = array();
preg_match_all("/\[".$key." (.+?)\]/", $content, $dat);
if(count($dat) > 0 && $dat[0] != array() && isset($dat[1])){
$i = 0;
$actual_string = $dat[0];
foreach($dat[1] as $temp){
$temp = explode(" ", $temp);
$params = array();
foreach ($temp as $d){
list($opt, $val) = explode("=", $d);
$params[$opt] = trim($val, '"');
}
$content = str_replace($actual_string[$i], $function($params), $content);
$i++;
}
}
}
return $content;
}
echo handleShortcodes($content, $shortcodes);
?>
The result:
Hello, my name is John an my age is 22.
Hello, my name is Carol an my age is 17.
This is actually tougher than it might appear on the surface. Andrew's answer works, but begins to break down if square brackets appear in the source text [like this, for example]. WordPress works by pre-registering a list of valid shortcodes, and only acting on text inside brackets if it matches one of these predefined values. That way it doesn't mangle any regular text that might just happen to have a set of square brackets in it.
The actual source code of the WordPress shortcode engine is fairly robust, and it doesn't look like it would be all that tough to modify the file to run by itself -- then you could use that in your application to handle the tough work. (If you're interested, take a look at get_shortcode_regex() in that file to see just how hairy the proper solution to this problem can actually get.)
A very rough implementation of your question using the WP shortcodes.php would look something like:
// Define the shortcode
function inlude_shortcode_func($attrs) {
$data = shortcode_atts(array(
'file' => 'default'
), $attrs);
return "Including File: {$data['file']}";
}
add_shortcode('include', 'inlude_shortcode_func');
// And then run your page content through the filter
echo do_shortcode('This is a document with [include file="header.html"] included!');
Again, not tested at all, but it's not a very hard API to use.
I have modified above function with wordpress function
function extractThis($short_code_string) {
$shortocode_regexp = "/(?P<shortcode>(?:(?:\\s?\\[))(?P<name>[\\w\\-]{3,})(?:\\s(?P<attrs>[\\w\\d,\\s=\\\"\\'\\-\\+\\#\\%\\!\\~\\`\\&\\.\\s\\:\\/\\?\\|]+))?(?:\\])(?:(?P<content>[\\w\\d\\,\\!\\#\\#\\$\\%\\^\\&\\*\\(\\\\)\\s\\=\\\"\\'\\-\\+\\&\\.\\s\\:\\/\\?\\|\\<\\>]+)(?:\\[\\/[\\w\\-\\_]+\\]))?)/u";
preg_match_all($shortocode_regexp, $short_code_string, $matches, PREG_SET_ORDER);
$shortcodes = array();
foreach ($matches as $i => $value) {
$shortcodes[$i]['shortcode'] = $value['shortcode'];
$shortcodes[$i]['name'] = $value['name'];
if (isset($value['attrs'])) {
$attrs = shortcode_parse_atts($value['attrs']);
$shortcodes[$i]['attrs'] = $attrs;
}
if (isset($value['content'])) {
$shortcodes[$i]['content'] = $value['content'];
}
}
return $shortcodes;
}
I think this one help for all :)
Updating the #Duco's snippet, As it seems like, it's exploding by spaces which ruins when we have some like
[Image source="myimage.jpg" alt="My Image"]
To current one:
function handleShortcodes($content, $shortcodes){
function read_attr($attr) {
$atList = [];
if (preg_match_all('/\s*(?:([a-z0-9-]+)\s*=\s*"([^"]*)")|(?:\s+([a-z0-9-]+)(?=\s*|>|\s+[a..z0-9]+))/i', $attr, $m)) {
for ($i = 0; $i < count($m[0]); $i++) {
if ($m[3][$i])
$atList[$m[3][$i]] = null;
else
$atList[$m[1][$i]] = $m[2][$i];
}
}
return $atList;
}
//Loop through all shortcodes
foreach($shortcodes as $key => $function){
$dat = array();
preg_match_all("/\[".$key."(.*?)\]/", $content, $dat);
if(count($dat) > 0 && $dat[0] != array() && isset($dat[1])){
$i = 0;
$actual_string = $dat[0];
foreach($dat[1] as $temp){
$params = read_attr($temp);
$content = str_replace($actual_string[$i], $function($params), $content);
$i++;
}
}
}
return $content;
}
$content = '[image source="one" alt="one two"]';
Result:
array(
[source] => myimage.jpg,
[alt] => My Image
)
Updated (Feb 11, 2020)
It appears to be following regex under preg_match only identifies shortcode with attributes
preg_match_all("/\[".$key." (.+?)\]/", $content, $dat);
to make it work with as normal [contact-form] or [mynotes]. We can change the following to
preg_match_all("/\[".$key."(.*?)\]/", $content, $dat);
I just had the same problem. For what I have to do, I am going to take advantage of existing xml parsers instead of writing my own regex. I am sure there are cases where it won't work
example.php
<?php
$file_content = '[include file="header.html"]';
// convert the string into xml
$xml = str_replace("[", "<", str_replace("]", "/>", $file_content));
$doc = new SimpleXMLElement($xml);
echo "name: " . $doc->getName() . "\n";
foreach($doc->attributes() as $key => $value) {
echo "$key: $value\n";
}
$ php example.php
name: include
file: header.html
to make it work on ubuntu I think you have to do this
sudo apt-get install php-xml
(thanks https://drupal.stackexchange.com/a/218271)
If you have lots of these strings in a file, then I think you can still do the find replace, and then just treat it all like xml.
please dont close this question as repeated one..........
I am new to php.
I am developing one tree grid in extjs.were i need to display field in tree format.so for front end i need to send the encoded data.
I want 2 functions for encoding and decoding a string variable,multidimensional array,variables with a set of delimiters.
For example if i am having an array.........
array(
array( "task" => "rose",
"duration" => 1.25,
"user" => 15
),
array( "task" => "daisy",
"duration" => 0.75,
"user" => 25,
),
array( "task" => "orchid",
"duration" => 1.15,
"user" => 7
),
array( "task" => "sunflower",
"duration" => 1.50,
"user" => 70
)
);
i want to encode all the array fields or single field as..........
array(
array( "task" => "rose",
"duration" => 1.25,
"user" => 15
),
array( "task" => "daisy",
"duration" => 0.75,
"user" => 25$sbaa,
),
array( "task" => "orchid",
"duration" => 1.15,
"user" => 7$!ass,
),
array( "task" => "sunflower",
"duration" => 1.50,
"user" => 70$!abc
)
);
So like this only i need to encode string,variables with delimiters.........
later all the encoded values to be decoded before its taken back to back end.....for this i have to use this plugin..........
encode.class.php...........
<?php
/*-------------------------
Author: Jonathan Pulice
Date: July 26th, 2005
Name: JPEncodeClass v1
Desc: Encoder and decoder using patterns.
-------------------------*/
class Protector
{
var $Pattern = "";
var $PatternFlip = "";
var $ToEncode = "";
var $ToDecode = "";
var $Decoded = "";
var $Encoded = "";
var $Bug = false;
var $DecodePattern = "";
function Debug($on = true)
{
$this->Bug = $on;
}
function Encode()
{
$ar = explode(":", $this->Pattern);
$enc = $this->ToEncode;
if ($this->Bug) echo "<!-- BEGIN ENCODING -->\n";
foreach ($ar as $num => $ltr)
{
switch ($ltr)
{
case "E":
$enc = base64_encode($enc);
break;
case "D":
$enc = base64_decode($enc);
break;
case "R":
$enc = strrev($enc);
break;
case "I":
$enc = $this->InvertCase($enc);
break;
}
if ($this->Bug) echo "<!-- {$ltr}: {$enc} -->\n";
}
if ($this->Bug) echo "<!-------------------->\n\n";
#$this->Encoded = ($enc == $this->Str) ? "<font color='red'>No Encoding/Decoding Pattern Detected!</font>" : $enc;
return $this->Encoded;
}
function Decode()
{
$pattern = ($this->DecodePattern != "") ? $this->DecodePattern : $this->Pattern;
//Reverse the pattern
$this->PatternFlip($pattern);
//make into an array
$ar = explode(":", $this->PatternFlip);
$t = ($this->Encoded == "") ? $this->ToDecode : $this->Encoded;
if ($this->Bug) echo "<!-- BEGIN DECODING -->\n";
foreach ($ar as $num => $ltr)
{
switch ($ltr)
{
case "E":
$t = base64_encode($t);
break;
case "D":
$t = base64_decode($t);
break;
case "R":
$t = strrev($t);
break;
case "I":
$t = $this->InvertCase($t);
break;
}
if ($this->Bug) echo "<!-- {$ltr}: {$t} -->\n";
}
if ($this->Bug) echo "<!-------------------->\n\n";
$this->Decoded = ($t == $this->Encoded) ? "<font color='red'>No Encoding/Decoding Pattern Detected!</font>" : $t;
return $this->Decoded;
}
function MakePattern($len = 10)
{
//possible letters
// E - Base64 Encode
// R - Reverse String
// I - Inverse Case
$poss = array('E','R', 'I');
//generate a string
for ( $i = 0 ; $i < $len ; $i++ )
{
$tmp[] = $poss[ rand(0,2) ];
}
//echo $str. "<br>";
//fix useless pattern section RR II
$str = implode(":", $tmp);
//fix
$str = str_replace( 'R:R:R:R:R:R' , 'R:E:R:E:R:E' , $str );
$str = str_replace( 'R:R:R:R:R' , 'R:E:R:E:R' , $str );
$str = str_replace( 'R:R:R:R' , 'R:E:R:E' , $str );
$str = str_replace( 'R:R:R' , 'R:E:R' , $str );
$str = str_replace( 'R:R' , 'R:E' , $str );
//fix
$str = str_replace( 'I:I:I:I:I:I' , 'I:E:I:E:I:E' , $str );
$str = str_replace( 'I:I:I:I:I' , 'I:E:I:E:I' , $str );
$str = str_replace( 'I:I:I:I' , 'I:E:I:E' , $str );
$str = str_replace( 'I:I:I' , 'I:E:I' , $str );
$str = str_replace( 'I:I' , 'I:E' , $str );
//string is good, set as pattern
$this->Pattern = $str;
return $this->Pattern; //if we need it
}
function PatternFlip($pattern)
{
//reverse the pattern
$str = strrev($pattern);
$ar = explode(":", $str);
foreach ($ar as $num => $ltr)
{
switch ($ltr)
{
case "E":
$tmp[] = "D";
break;
case "D":
$tmp[] = "E";
break;
case "R":
$tmp[] = "R";
break;
case "I":
$tmp[] = "I";
break;
}
}
$rev = implode(":", $tmp);
$this->PatternFlip = $rev;
return $this->PatternFlip;
}
// This is my custom Case Invertor!
// if you would like to use this in a script, please credit it to me, thank you
function InvertCase($str)
{
//Do initial conversion
$new = strtoupper( $str );
//spluit into arrays
$s = str_split( $str );
$n = str_split( $new );
//now we step through each letter, and if its the same as before, we swap it out
for ($i = 0; $i < count($s); $i++)
{
if ( $s[$i] === $n[$i] ) //SWAP THE LETTER
{
//ge the letter
$num = ord( $n[$i] );
//see if the ord is in the alpha ranges ( 65 - 90 | 97 - 122 )
if ( ( $num >= 65 AND $num <= 90 ) OR ( $num >= 97 AND $num <= 122 ) )
{
if ($num < 97 ) { $num = $num + 32; }
else { $num = $num - 32; }
$newchr = chr($num);
$n[$i] = $newchr;
}
}
}
//join the new string back together
$newstr = implode("", $n);
return $newstr;
}
}
?>
............
from this plugin i need to use encode and decode functions for my functions.........
if anyone can help me on this.......it will be very much useful for me.......
Why don't you use json_encode? Just do
$str=json_encode($array);
Then, send the data, and at the other end do
$array=json_decode($str);
Okay, let's break down the problem.
You have an array. Each element in the array is a hash. One (or more) of the values in that hash has to be encoded using that horrible abomination of a library. But the library can't process arrays.
We'll have to process the array ourselves.
<rant>
Before we begin, I'd just like to again express how horribly that "Protector" code is designed. It's written for PHP4 and is effectively spaghetti code wrapped in a class. It mis-uses properties, almost as if the user had some sort of mis-remembering about how Java's instance variables work and somehow thought it would be appropriate or sane to use PHP in the same way. If the author of the code doesn't look back on that revolting chunk of bytes now with utter disdain, something is severely wrong with him.
</rant>
I'm going to base my knowledge of this class on this copy of it, as the one you've provided is formatted even worse than the original.
First, let's create a list of inner array keys that we need to encode.
$keys_to_encode = array( 'user' );
Your example encoding lists only the user key as encodable. If you need to encode others, just add more elements to that array.
Now, let's prepare our "Protector." It seems to want you to either specify a pattern, or use the MakePattern method to have it create one. We're going to manually-specify one because MakePattern can come up with effectively useless combinations.
$stupid = new Protector();
$stupid->Pattern = 'E:I:E:R:D:I:E';
This will base64-encode, flip the case, base64 again, reverse it, un-base64, flip the case, and then re-base64. Be aware that PHP's base64 decoder "correctly" ignores bad padding and unexpected characters, which is the only reason the base64-reverse-unbase64 thing will work. The resulting string will look like gibberish to people that don't know what base64 looks like, and un-base64 to gibberish for people that to know what base64 looks like.
If you need to encode the values in a certain way, you'd do so by just changing the pattern. It's important that you either hard-code the pattern or store it somewhere with the data, because without it, you'll have a hard time doing the decode. (I mean, it can be done by hand, but you don't want to have to do that.) I expect that your boss is going to give you specific instructions on the pattern, given that you don't have an option in using this utter failure at a class.
Now it's time to process our data. Let's pretend that $in contains your original array.
$out = array();
foreach($in as $k => $target) {
foreach($keys_to_encode as $target_key) {
$stupid->ToEncode = $target[ $target_key ];
$target[ $target_key ] = $stupid->Encode();
}
$out[$k] = $target;
}
This loops through the array of hashes, then inside each hash, only the keys we want to encode are encoded. The encoded hash is placed in a new array, $out. This is what you'd pass to your tree widget.
Decoding is just as easy. You've stated that your goal is letting users edit certain data in the tree widget, and you seem to want to protect the underlying keys. This tells me that you probably only need to deal with one of the hashes at a time. Therefore, I'm going to write this decode sample using only one value, $whatever.
$stupidest = new Protector();
$stupidest->Pattern = 'E:I:E:R:D:I:E'; // SAME PATTERN!
$stupidest->ToDecode = $whatever;
$decoded = $stupidest->Decode();
Again, it's critical that you use the same decode pattern here.
As for the actual interaction with the tree widget, you're on your own there. I know only enough about ExtJS to know that it exists and that the GUI creators for it are really fun to play with.
Is it possible to pull track info from an audio stream using PHP? I've done some digging and the closest function I can find is stream_get_transports but my host doesn't support http transports via fsockopen() so I'll have to do some more tinkering to see what else that function returns.
Currently, I'm trying to pull artist and track metadata from an AOL stream.
This is a SHOUTcast stream, and yes it is possible. It has absolutely nothing to do with ID3 tags. I wrote a script awhile ago to do this, but can't find it anymore. Just last week I helped another guy who had a fairly complete script to do the same thing, but I can't just post the source to it, as it isn't mine. I will however get you in touch with him, if you e-mail me at brad#musatcha.com.
Anyway, here's how to do it yourself:
The first thing you need to do is connect to the server directly. Don't use HTTP. Well, you could probably use cURL, but it will likely be much more hassle than its worth. You connect to it with fsockopen() (doc). Make sure to use the correct port. Also note that many web hosts will block a lot of ports, but you can usually use port 80. Fortunately, all of the AOL-hosted SHOUTcast streams use port 80.
Now, make your request just like your client would.
GET /whatever HTTP/1.0
But, before sending <CrLf><CrLf>, include this next header!
Icy-MetaData:1
That tells the server that you want metadata. Now, send your pair of <CrLf>.
Ok, the server will respond with a bunch of headers and then start sending you data. In those headers will be an icy-metaint:8192 or similar. That 8192 is the meta interval. This is important, and really the only value you need. It is usually 8192, but not always, so make sure to actually read this value!
Basically it means, you will get 8192 bytes of MP3 data and then a chunk of meta, followed by 8192 bytes of MP3 data, followed by a chunk of meta.
Read 8192 bytes of data (make sure you are not including the header in this count), discard them, and then read the next byte. This byte is the first byte of meta data, and indicates how long the meta data is. Take the value of this byte (the actual byte with ord() (doc)), and multiply it by 16. The result is the number of bytes to read for metadata. Read those number of bytes into a string variable for you to work with.
Next, trim the value of this variable. Why? Because the string is padded with 0x0 at the end (to make it fit evenly into a multiple of 16 bytes), and trim() (doc) takes care of that for us.
You will be left with something like this:
StreamTitle='Awesome Trance Mix - DI.fm';StreamUrl=''
I'll let you pick your method of choice for parsing this. Personally I'd probably just split with a limit of 2 on ;, but beware of titles that contain ;. I'm not sure what the escape character method is. A little experimentation should help you.
Don't forget to disconnect from the server when you're done with it!
There are lots of SHOUTcast MetaData references out there. This is a good one: http://www.smackfu.com/stuff/programming/shoutcast.html
Check this out: https://gist.github.com/fracasula/5781710
It's a little gist with a PHP function that lets you extract MP3 metadata (StreamTitle) from a streaming URL.
Usually the streaming server puts an icy-metaint header in the response which tells us how often the metadata is sent in the stream. The function checks for that response header and, if present, it replaces the interval parameter with it.
Otherwise the function calls the streaming URL respecting your interval and, if any metadata isn't present, then it tries again through recursion starting from the offset parameter.
<?php
/**
* Please be aware. This gist requires at least PHP 5.4 to run correctly.
* Otherwise consider downgrading the $opts array code to the classic "array" syntax.
*/
function getMp3StreamTitle($streamingUrl, $interval, $offset = 0, $headers = true)
{
$needle = 'StreamTitle=';
$ua = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36';
$opts = [
'http' => [
'method' => 'GET',
'header' => 'Icy-MetaData: 1',
'user_agent' => $ua
]
];
if (($headers = get_headers($streamingUrl))) {
foreach ($headers as $h) {
if (strpos(strtolower($h), 'icy-metaint') !== false && ($interval = explode(':', $h)[1])) {
break;
}
}
}
$context = stream_context_create($opts);
if ($stream = fopen($streamingUrl, 'r', false, $context)) {
$buffer = stream_get_contents($stream, $interval, $offset);
fclose($stream);
if (strpos($buffer, $needle) !== false) {
$title = explode($needle, $buffer)[1];
return substr($title, 1, strpos($title, ';') - 2);
} else {
return getMp3StreamTitle($streamingUrl, $interval, $offset + $interval, false);
}
} else {
throw new Exception("Unable to open stream [{$streamingUrl}]");
}
}
var_dump(getMp3StreamTitle('http://str30.creacast.com/r101_thema6', 19200));
I hope this helps!
Thanks a lot for the code fra_casula. Here is a slightly simplified version running on PHP <= 5.3 (the original is targeted at 5.4). It also reuses the same connection resource.
I removed the exception because of my own needs, returning false if nothing is found instead.
private function getMp3StreamTitle($steam_url)
{
$result = false;
$icy_metaint = -1;
$needle = 'StreamTitle=';
$ua = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36';
$opts = array(
'http' => array(
'method' => 'GET',
'header' => 'Icy-MetaData: 1',
'user_agent' => $ua
)
);
$default = stream_context_set_default($opts);
$stream = fopen($steam_url, 'r');
if($stream && ($meta_data = stream_get_meta_data($stream)) && isset($meta_data['wrapper_data'])){
foreach ($meta_data['wrapper_data'] as $header){
if (strpos(strtolower($header), 'icy-metaint') !== false){
$tmp = explode(":", $header);
$icy_metaint = trim($tmp[1]);
break;
}
}
}
if($icy_metaint != -1)
{
$buffer = stream_get_contents($stream, 300, $icy_metaint);
if(strpos($buffer, $needle) !== false)
{
$title = explode($needle, $buffer);
$title = trim($title[1]);
$result = substr($title, 1, strpos($title, ';') - 2);
}
}
if($stream)
fclose($stream);
return $result;
}
This is the C# code for getting the metadata using HttpClient:
public async Task<string> GetMetaDataFromIceCastStream(string url)
{
m_httpClient.DefaultRequestHeaders.Add("Icy-MetaData", "1");
var response = await m_httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
m_httpClient.DefaultRequestHeaders.Remove("Icy-MetaData");
if (response.IsSuccessStatusCode)
{
IEnumerable<string> headerValues;
if (response.Headers.TryGetValues("icy-metaint", out headerValues))
{
string metaIntString = headerValues.First();
if (!string.IsNullOrEmpty(metaIntString))
{
int metadataInterval = int.Parse(metaIntString);
byte[] buffer = new byte[metadataInterval];
using (var stream = await response.Content.ReadAsStreamAsync())
{
int numBytesRead = 0;
int numBytesToRead = metadataInterval;
do
{
int n = stream.Read(buffer, numBytesRead, 10);
numBytesRead += n;
numBytesToRead -= n;
} while (numBytesToRead > 0);
int lengthOfMetaData = stream.ReadByte();
int metaBytesToRead = lengthOfMetaData * 16;
byte[] metadataBytes = new byte[metaBytesToRead];
var bytesRead = await stream.ReadAsync(metadataBytes, 0, metaBytesToRead);
var metaDataString = System.Text.Encoding.UTF8.GetString(metadataBytes);
return metaDataString;
}
}
}
}
return null;
}
UPDATE:
This is an update with a more appropriate solution to the question. The original post is also provided below for information.
The script in this post, after some error correction, works and extracts the stream title using PHP:
PHP script to extract artist & title from Shoutcast/Icecast stream.
I had to make a couple of changes, because the echo statements at the end were throwing an error. I added two print_r() statements after the function, and $argv[1] in the call so you can pass the URL to it from the command line.
<?php
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.'.';
print_r($theaders);
print_r($metadata);
}
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($argv[1]); // get metadata
/*
echo "Meta Interval: ".$t->icymetaint;
echo "\n";
echo 'Current Track: '.$t->streamtitle;
*/
?>
With the updated code, it prints the arrays of header and streamtitle info. If you only want the now_playing track, then comment out the two print_r() statements, and uncomment the echo statements at the end.
#Example: run this command:
php getstreamtitle.php http://162.244.80.118:3066
#and the result is...
Array
(
[0] => HTTP/1.0 200 OK
[1] => icy-notice1:<BR>This stream requires Winamp<BR>
[2] => icy-notice2:SHOUTcast DNAS/posix(linux x64) v2.6.0.750<BR>
[3] => Accept-Ranges:none
[4] => Access-Control-Allow-Origin:*
[5] => Cache-Control:no-cache,no-store,must-revalidate,max-age=0
[6] => Connection:close
[7] => icy-name:
[8] => icy-genre:Old Time Radio
[9] => icy-br:24
[10] => icy-sr:22050
[11] => icy-url:http://horror-theatre.com
[12] => icy-pub:1
[13] => content-type:audio/mpeg
[14] => icy-metaint:8192
[15] => X-Clacks-Overhead:GNU Terry Pratchett
[16] =>
)
StreamTitle='501026TooHotToLive';
Here is the original post using python and vlc
The PHP solution kept searching but never returned a response for me.
This is not PHP as requested, but may help others looking for a way to extract the 'now_playing' info from live streams.
If you only want the 'now_playing' info, you can edit the script to return that.
The python script extracts the metadata (including the 'now_playing' track) using VLC. You need VLC and the python libraries: sys, telnetlib, os, time and socket.
#!/usr/bin/python
# coding: utf-8
import sys, telnetlib, os, time, socket
HOST = "localhost"
password = "admin"
port = "4212"
def check_port():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
res = sock.connect_ex((HOST, int(port)))
sock.close()
return res == 0
def checkstat():
if not check_port():
os.popen('vlc --no-audio --intf telnet --telnet-password admin --quiet 2>/dev/null &')
while not check_port():
time.sleep(.1)
def docmd(cmd):
tn = telnetlib.Telnet(HOST, port)
tn.read_until(b"Password: ")
tn.write(password.encode('utf-8') + b"\n")
tn.read_until(b"> ")
tn.write(cmd.encode('utf-8') + b"\n")
ans=tn.read_until(">".encode("utf-8"))[0:-3]
return(ans)
tn.close()
def nowplaying(playing):
npstart=playing.find('now_playing')
mystr=playing[npstart:]
npend=mystr.find('\n')
return mystr[:npend]
def metadata(playing):
fstr='+----'
mstart=playing.find(fstr)
mend=playing.find(fstr,mstart+len(fstr))
return playing[mstart:mend+len(fstr)]
checkstat()
docmd('add '+sys.argv[1])
playing=""
count=0
while not 'now_playing:' in playing:
time.sleep(.5)
playing=docmd('info')
count+=1
if count>9:
break
if playing == "":
print("--Timeout--")
else:
print(metadata(playing))
docmd('shutdown')
Example, extract metadata from Crypt Theater Station:
./radiometatdata.py http://107.181.227.250:8026
Response:
+----[ Meta data ]
|
| title: *CRYPT THEATER*
| filename: 107.181.227.250:8026
| genre: Old Time Radio
| now_playing: CBS Radio Mystery Theatre - A Ghostly Game of Death
|
+----