I have a json api I'm trying to feed to several functions. I'm not entirely sure how to make the file_get_contents global so that it can be accessed by multiple functions at once.
Here is my current PHP code:
function getVideoTitle($getVideoID) {
$json_output = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=".$getVideoID."&key={MY_KEY}&fields=items(id,snippet(title,description),statistics)&part=snippet,statistics");
$json = json_decode($json_output, true);
$video_title = $json['items'][0]['snippet']['title']; // Video Title
return $video_title;
}
function getVideoDesc($getVideoID) {
$json_output = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=".$getVideoID."&key={MY_KEY}&fields=items(id,snippet(title,description),statistics)&part=snippet,statistics");
$json = json_decode($json_output, true);
$video_description = $json['items'][0]['snippet']['description']; //Description
return $video_description;
}
echo getVideoTitle($getVideoID);
echo getVideoDesc($getVideoID);
If I remove the two $json variables and place them outside of the function I get an error that it couldn't find the variable $json.
Also, would making it a global variable make it run faster? Retrieving the API is currently running pretty slowly. Would it be wiser to switch to Javascript..? Thanks.
If the $json is supposed to be constant, then I believe you're better to create a class, since you need to provide the $getVideoID for the ID of the video, and additionally you have the ability to change the video conveniently :)
<?php
class MyVideoClass {
private $json = null;
public function __construct($videoID) {
$this->changeVideo($videoID);
}
public function changeVideo($videoID) {
$json_output = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=".$videoID."&key={MY_KEY}&fields=items(id,snippet(title,description),statistics)&part=snippet,statistics");
$this->json = json_decode($json_output, true);
}
function getVideoTitle() {
$video_title = $this->json['items'][0]['snippet']['title']; // Video Title
return $video_title;
}
function getVideoDesc() {
$video_description = $this->json['items'][0]['snippet']['description']; //Description
return $video_description;
}
}
// somewhere:
$myVideo = new MyVideoClass($yourVideoID);
echo $myVideo->getVideoTitle();
echo $myVideo->getVideoDesc();
// sometime else
$myVideo->changeVideo($anotherVideoID);
echo $myVideo->getVideoTitle();
echo $myVideo->getVideoDesc();
here what i have wrote for you
<?php
class Video{
private $data;
public function __construct($videoId, $key){
$json_output = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=".$videoId."&key=".$key."&fields=items(id,snippet(title,description),statistics)&part=snippet,statistics");
isset($json_output) ? $this->data = $json_output : $this->data = false;
}
public function getTitle(){
if($this->data){
$video_title = $this->data['items'][0]['snippet']['title']; // Video Description
return $video_title;
}else{
return false;
}
}
public function getDesc(){
if($this->data){
$video_desc = $this->data['items'][0]['snippet']['description']; // Video Title
return $video_desc;
}else{
return false;
}
}
public function change($videoId, $key){
$this->__construct($videoId, $key);
}
}
Usage Example:
include('video.php'); // if you going to save the class in separate file
$video = new Video('Video-Id-Here', 'your-key');
echo $video->getTitle().'<br/>';
echo $video->getDesc();
//new video
$video->change('new-video-id', 'new-key');
echo $video->getTitle().'<br/>';
echo $video->getDesc();
and you can add more functions to the class
Related
why my public variable cannot read by other function?
my public variable :
public $dataku = array();
first i set data to my public variable from model:
function cari() {
$penerima = $this->input->post('penerima');
$tanggal = $this->input->post('tanggal');
$tanggal2 = $this->input->post('tanggal2');
$id_komoditas = $this->input->post('id_komoditas');
$this->dataku['judul'] = $this->judul;
$this->dataku['pencarian'] = $this->mdl->get_data_antara_tanggal($penerima, $tanggal, $tanggal2, $id_komoditas);
$this->dataku['url'] = $this->url;
$title = "Data ".$this->judul;
$subtitle = $this->url;
$content = $this->load->view('cari.php', $this->dataku, true);
$this->load_content($title, $subtitle, $content);
}
but, when i want to read the public variable data again, it hasnt a data :
function check_data(){
$data = isset($this->dataku['pencarian']) ? $this->dataku['pencarian'] : 'no data';
print_r($data);
}
please, i need your help.
you need to access the class properties with $this. Change the following lines:
$this->dataku['judul'] = $this->judul;
$this->dataku['pencarian'] = $this->mdl->get_data_antara_tanggal($penerima, $tanggal, $tanggal2, $id_komoditas);
$this->dataku['url'] = $this->url;
Also edit the following (you have an extra $):
function check_data(){
$data = isset($this->dataku['pencarian']) ? $this->dataku['pencarian'] : 'no data';
print_r($data);
}
i have little problem with XML. My XML file is look like this:
http://pastebin.com/MQUB2W2B i user pastebin because this site don't support xml code.. ://
so i need to select source mount "/stream" and other source mount "/". And my PHP code look like this:
Class stream {
Public Function __construct($host, $path, $user, $pass, $mpoint){
$this->host = $host;
$this->path = $path;
$this->user = $user;
$this->password = $pass;
$this->mpoint = $mpoint;
$this->url = "http://{$this->user}:{$this->password}#{$this->host}/{$this->path}";
$this->xml = simplexml_load_file($this->url);
}
Public Function audio($url, $format){
return print "<audio controls> <source src=\"{$url}\" type=\"audio/{$format}\"> </audio>";
}
Public Function stream_meta(){
$xml = $this->xml->registerXPathNamespace('test', '/{$this->mpoint}');
$result = $xml->xpath('test:artist');
return $result;
}
Public Function nowplay(){
return $this->xml->source[0]->artist;
}
Public Function download($format){
$link = "http://{$this->host}/{$this->mpoint}";
if($format == "m3u"){
return "{$link}.m3u";
}
elseif($format == "xspf"){
return "{$link}.xspf";
}
elseif($format == "vclt"){
return "{$link}.vclt";
}
return false;
}
}
So now i asking what i do wrong or what i can do better? i need to select artist data and know what is the source mount "?what is this?". I really need help. I don't know what i can do and i don't invent other way to do this. I am so tired and i am really need help! Please, can anyone help me? I don't want to use "nowplay()" function. because source mount "/example" change sometimes...
I'm not entirely clear on what you are trying to achieve, but here is a basic example of getting the mount and artist of each source in the XML:
function sources(){
foreach($this->xml->source as $source) {
echo "Mount: " . $source->attributes()['mount'] . '<br>';
echo "Artist: " . $source->artist . '<br>';
}
}
Or to find the artist for a source:
$source = $this->find_source('/stream');
$artist = $source->artist;
function find_source($s){
foreach($this->xml->source as $source) {
if ($source->attributes()['mount'] == $s) {
return $source;
}
}
}
Alternatively, you could do the same with XPath without needing to use a loop. For example:
function find_source($s){
return $this->xml->xpath('/icestats/source[#mount="'.$s.'"]')[0];
}
I am a beginner in PHP OOP.
I was wondering what is the best practice in PHP OOP and classes. Keep values in a Variables ($var) or keep them in the object ($this->var).
As you can see in below code I set the variables ($this->var) in methods and ,therefore, do not need to return anything from that method.
Is this a correct way of doing it or do I need to return somthing from method? and pass that value to the next method?
Below is a simple curl class for API that extracts a clients email address by using a code.
Pay specific attention to extract_ib_email() Method, no variable is passed to functions (Methods). Is this correct and is there a better way of doing it please?
//Parent Class
class CurlRequest
{
/* get the data from a URL */
protected function curl_get_data() {
$ch = curl_init();
//$timeout = 5;
curl_setopt($ch, CURLOPT_VERBOSE, $this->curloptVERBOSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->curloptSSLVERIFYPEER);
curl_setopt($ch, CURLOPT_URL, $this->curlURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $this->curloptRETURNTRANSFER);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout);
$data = curl_exec($ch);
if ($data === FALSE) {
printf("cUrl error (#%d): %s<br>\n", curl_errno($ch),
htmlspecialchars(curl_error($ch)));
}
//echo "<pre>"; print_r($data); echo "</pre>";
//var_dump($data);
curl_close($ch);
$this->data = $data;
return $data;
}
}
class GetIBEmail extends CurlRequest
{
private $ibRef;
function __construct($ibRef)
{
// Set Variables
$this->baseURL = 'https://www.example.com/api/iel/';
$this->ibRef = $ibRef;
//$this->ibCode = $ibCode;
//set curl options for this request specifically
$this->timeout = $timeout = 5;
$this->curloptVERBOSE = $curlopt_VERBOSE = true;
$this->curloptSSLVERIFYPEER = $curlopt_SSL_VERIFYPEER = false;
$this->curloptRETURNTRANSFER = $curlopt_RETURNTRANSFER = 1;
}
// IB Code form is like ib_xxx need to get the last 3 letters
private function getIBCode(){
$ibRefBits = explode('_', $this->ibRef);
$this->ibCode = $ibRefBits[1];
//return $this->ibCode;
}
//construct the curl url using the IB code
private function construct_ib_curl_url(){
//$url = 'https://www.example.com/api/iel/xxx';
//$url = $this->baseURL . $this->ibCode;
$this->curlURL = $this->baseURL . $this->ibCode;
//return $url;
}
// extract email from returned curl response
public function extract_ib_email() {
$this->getIBCode();
$this->construct_ib_curl_url();
$this->curl_get_data();
$resArr = array();
$resArr = json_decode($this->data);
echo "<pre>"; print_r($resArr); echo "</pre>";
$ib_email = $resArr[0]->email;
$this->ib_email = $ib_email;
return $ib_email;
}
}
//Set ibCode
$ibCode = 'ib_xxx'; //$_SESSION['ib_code'];
$ibEmail = new GetIBEmail($ibCode); //pass value to the construct function
echo '<br>' . $ibEmail->extract_ib_email() . '<br>';
I've been looking around hoping I could find the issue I'm stumbling upon... However I couldn't find it. I've made a class in PHP, within that class there is a function that connects to an API retrieving JSON data (this function has been tested and works like a charm). However now I'm trying to seperate the objects of the JSON data I receive into different functions.
I've only managed to parse the data now through a foreach and echo, but it'd be a hassle to do it like that constantly.
This is what it currently looks like so you get an idea.
EDIT
Issue has been resolved, the public function foo(); Had and $info variable which had a json_decode(); which interupted the next function to split the data.
class parseData{
var $name;
var $domain;
public function foo($name, $domain)
{
$this->name = $name;
$this->domain = $domain;
$ch = curl_init();
$user_agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31';
$request_headers = array();
$request_headers[] = 'User-Agent: ' . $user_agent;
$request_headers[] = 'Accept: text/html,application/xhtml+xml,application/xml,application/json;q=0.9,*/*;q=0.8';
curl_setopt($ch, CURLOPT_URL, "https://www.xxx." . $domain . "/api/public/users?name=" . $name . "");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, "https://www.xxx." . $domain . "/api/public/users?name=" . $name);
$id = json_decode(curl_exec($ch));
if (isset($id) && $id->profileVisible == 1) {
curl_setopt($ch, CURLOPT_URL, "https://www.xxx." . $domain . "/api/public/users/" . $id->uniqueId . "/profile");
$info = curl_exec($ch);
} else
$info = false;
curl_close($ch);
return $info;
}
public $response = array(), $user = array(), $friends = array(), $groups = array(), $rooms = array(), $badges = array();
public function __construct(){
$this->response = $this->foo("user", "nl");
$this->init();
}
// this function will split data into sub variables
private function init(){
$this->response =json_decode(file_get_contents($this->response), TRUE);
$this->user = $this->response['user'];
$this->friends = $this->response['friends'];
$this->groups = $this->response['groups'];
$this->rooms = $this->response['rooms'];
$this->badges = $this->response['badges'];
// free main response object
unset($this->response);
}
public function uid(){
echo $this->user['uniqueId'];
}
public function name(){
echo $this->user['name'];
}
public function membersince(){
echo $this->user['memberSince'];
}
public function motto(){
echo $this->user['motto'];
}
public function figure(){
echo $this->user['figureString'];
}
//this function will manipulate USER data.
public function user(){
echo "Naam: ".$this->user['name'].'<br/>';
echo "Motto: ".$this->user['motto'].'<br/>';
echo "Lid sinds: ".$this->user['memberSince'].'<br/>';
echo "Unique ID: ".$this->user['uniqueId'].'<br/>';
echo "figureString: ".$this->user['figureString'].'<br/>';
foreach($this->user['selectedBadges'] as $selectedBadge){
echo 'Badge index: '. $selectedBadge['badgeIndex'];
echo 'Badge code: '. $selectedBadge['code'];
echo 'Badge naam: '. $selectedBadge['name'];
echo 'Badge beschrijving: '. $selectedBadge['description'];
}
}
public function friends(){
//do stuff with $this->friends.
}
public function groups(){
//do stuff with $this->groups
}
//and other functions like badges and rooms etc.
}
$parser = new parseData();
$parser->user();
The API sends different objects back and I'd like to seperate them into different functions as "user", "friends", "groups" etc. in order to retrieve all the strings out of those objects. So my question is, is it possible to parse API data through different functions within the same class? If so, how do I do this? And will calling the function be an easier task to do as well or will it just be a hassle like doing the foreach method?
So, I've looked into your json and you can like this
class parseData{
public $response = array(), $user = array(), $friends = array(), $groups = array(), $rooms = array(), $badges = array();
public function __construct(){
$this->response = call_your_function_get_api_response();
$this->init();
}
// this function will split data into sub variables
private function init(){
$this->response = json_decode(file_get_contents('json.json'), TRUE);
//I'm using file get contents here, as I've stored your json into file.
// but you'll have to do like this
//$this->response = json_decode($this->response, TRUE);
$this->user = $this->response['user'];
$this->friends = $this->response['friends'];
$this->groups = $this->response['groups'];
$this->rooms = $this->response['rooms'];
$this->badges = $this->response['badges'];
// free main response object
unset($this->response);
}
/*
* I'm updating here with new function name(), so to print name only do this.
*/
public function name(){
echo "Name: ".$this->user['name'].'<br/>'; //This will print name only.
}
//this function will manipulate USER data.
public function user(){
echo "User's Unique ID: ".$this->user['uniqueId'].'<br/>';
echo "Name: ".$this->user['name'].'<br/>';
echo "figureString: ".$this->user['figureString'].'<br/>';
foreach($this->user['selectedBadges'] as $selectedBadge){
echo 'Badge index: '. $selectedBadge['badgeIndex'];
echo 'Badge code: '. $selectedBadge['code'];
echo 'Badge name: '. $selectedBadge['name'];
echo 'Badge description: '. $selectedBadge['description'];
}
}
public function friends(){
//do stuff with $this->friends.
}
public function groups(){
//do stuff with $this->groups
}
//and other functions like badges and rooms etc.
}
$parser = new parseData();
$parser->user();
/*
* and you can call function like this
* $parser->friends(); will process only friends data from json response
* $parser->groups(); will process only groups data from json response.
* ... rest of functions ...
*/
I've tested this with one iteration of stuff using users() function.
here is output
Edit
I've updated class with a new method name() so now to print only name,
$parser->name();
Another Edit
as per your comment
I'm putting __construct() code here again.
public function __construct(){
$get = new foo();
$this->response = $get->bar("person", "nl");
$this->init();
}
and rest of the things are same.
$parser = new parseData();
$parser->user();
$parser->name(); //will display name only.
putting all together
you need to update two functions
public function __construct(){
$this->response = json_decode($this->foo("user", "nl"), TRUE);
$this->init();
}
and in init() comment out the first line as it's not needed any more.
Hope this will help you.
I am trying to store some data as an array in the session but the function does not seem to be working.it does not throw any error but every time i add data to it, it just overwrites the previous data. I am using yii and here is the action
public function actionStoreProducts($name)
{
$name=trim(strip_tags($name));
if(!empty($name))
{
if(!isset(Yii::app()->session['_products']))
{
Yii::app()->session['_products']=array($name);
echo 'added';
}
else
{
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
Yii::app()->session['products'] = $myProducts;
echo 'added';
}
}
Can anyone suggest me how can i achieve the desired result?
Please correct your code like this .
public function actionStoreProducts($name) {
$name = trim(strip_tags($name));
if (!empty($name)) {
if (!isset(Yii::app()->session['_products'])) {
Yii::app()->session['_products'] = array($name);
echo 'added';
} else {
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
Yii::app()->session['_products'] = $myProducts;
echo print_r(Yii::app()->session['_products']);
echo 'added';
}
}
}
session property read-only
i think the correct aproach is :
function actionStoreProducts($name) {
$session = new CHttpSession; //add this line
$session->open(); //add this line
$name = trim(strip_tags($name));
if (!empty($name)) {
if (!isset(Yii::app()->session['_products'])) {
$session->add('_products', array($name)); //replace this line
echo 'added';
} else {
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
$session->add('_products', $myProducts); //replace this line
echo 'added';
}
}
}
first get an variable into $session['somevalue'] ,then sore in array variable, Use Like IT:-
$session = new CHttpSession;
$session->open();
$myval = $session['somevalue'];
$myval[] = $_POST['level'];
$session['somevalue'] = $myval;