I am facing a problem for last few hours but not come to the solution. I am trying to get youtube channel by name using php-youtube-api reference link in laravel. But I am only getting single channel in output. But i want a list of channels related name like this. When i search for any channel having name "soccerit" return me
stdClass Object
(
[kind] => youtube#channel
[etag] => "kjEFmP90GvrCl8BObMQtGoRfgaQ/I7mfLJg2NMc3uuc6rLgQDgQ-_3g"
[id] => UClENohulIkpi8JV18UJIPeg
[snippet] => stdClass Object
(
[title] => soccer
[description] =>
[publishedAt] => 2005-11-07T19:54:17.000Z
[thumbnails] => stdClass Object
(
[default] => stdClass Object
(
[url] => https://yt3.ggpht.com/-NcE9VxoZBwQ/AAAAAAAAAAI/AAAAAAAAAAA/F923oDS5GIc/s88-c-k-no/photo.jpg
)
[medium] => stdClass Object
(
[url] => https://yt3.ggpht.com/-NcE9VxoZBwQ/AAAAAAAAAAI/AAAAAAAAAAA/F923oDS5GIc/s240-c-k-no/photo.jpg
)
[high] => stdClass Object
(
[url] => https://yt3.ggpht.com/-NcE9VxoZBwQ/AAAAAAAAAAI/AAAAAAAAAAA/F923oDS5GIc/s240-c-k-no/photo.jpg
)
)
)
[contentDetails] => stdClass Object
(
[relatedPlaylists] => stdClass Object
(
[uploads] => UUlENohulIkpi8JV18UJIPeg
)
[googlePlusUserId] => 107844494883714037142
)
[statistics] => stdClass Object
(
[viewCount] => 763486
[commentCount] => 134
[subscriberCount] => 1478
[hiddenSubscriberCount] =>
[videoCount] => 32
)
)
Thanks in advance.
my code is :
YoutubeController.php
class YoutubeController extends BaseController {
public function index()
{
$youtube = new Madcoda\Youtube(array('key' => ##Yuxw99Ka7szK4'));
$channel = $youtube->getChannelByName($data['q']);
print_r($channel);
}
}
Youtube.php
public function getChannelByName($username, $optionalParams = false)
{
$API_URL = $this->getApi('channels.list');
$params = array(
'forUsername' => $username,
'part' => 'id,snippet,contentDetails,statistics,invideoPromotion'
);
if($optionalParams){
$params = array_merge($params, $optionalParams);
}
$apiData = $this->api_get($API_URL, $params);
return $this->decodeSingle($apiData);
}
public function api_get($url, $params)
{
//set the youtube key
$params['key'] = $this->youtube_key;
//boilerplates for CURL
// $url = "https://gdata.youtube.com/feeds/api/channels";
$a = $url . (strpos($url, '?') === false ? '?' : '') . http_build_query($params);
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, $a);
if (strpos($url, 'https') === false) {
curl_setopt($tuCurl, CURLOPT_PORT, 80);
} else {
curl_setopt($tuCurl, CURLOPT_PORT, 443);
}
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tuCurl, CURLOPT_SSL_VERIFYPEER, 0);
$tuData = curl_exec($tuCurl);
if (curl_errno($tuCurl)) {
throw new \Exception('Curl Error : ' . curl_error($tuCurl));
}
return $tuData;
}
It seems you are using wrong method. Method getChannelByName returns channel with exact name. If you want to search channels you should use:
// Search playlists, channels and videos, Return an array of PHP objects
$channels = $youtube->search($data['q']);
or if you want co search only videos you should choose:
// Search only Videos, Return an array of PHP objects
$channels = $youtube->searchVideos($data['q']);
Related
I am trying to remove all the empty rows from a csv and make it downloadable. In this process, there is no involvement of database/model.
My flow looks like:
1) Import csv file.
2) Filter empty rows.
3) Export the data after all the empty rows are removed.
My code looks like:
Controller
public function formatCSV()
{
$path = storage_path('app/files/') . 'example.csv';
Excel::import(new FormatCSV, $path);
}
app/Imports/FormatCSV
<?php
namespace App\Imports;
use App\Exports\ExportFormattedCSV;
use App\Http\Services\AmenityService;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Excel;
class FormatCSV implements ToArray, WithChunkReading
{
private $table,$service,$model;
public function __construct()
{
$this->service = new AmenityService();
}
public function array(Array $rows)
{ $rec_arr = array();
foreach ($rows as $row)
{
$rec_arr[] = array_values($row);
}
$records_arr = $this->service->trimArray($rec_arr);
$export = new ExportFormattedCSV($records_arr);
//print_r($export);
return Excel::download($export, 'csv.csv');
}
public function chunkSize(): int
{
return 10;
}
}
trimArray function
public function trimArray($arr)
{
$final = array();
foreach($arr as $k => $v)
{
if(array_filter($v)) {
$final[] = $v;
}
}
return $final;
}
app/Exports/ExportFormattedCSV
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromArray;
class ExportFormattedCSV implements FromArray
{
protected $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function array(): array
{
return $this->data;
}
}
With this code it does nothing, shows blank at the end.
However, if I uncomment the line print_r($export)
It shows data as:
App\Exports\ExportFormattedCSV Object
(
[data:protected] => Array
(
[0] => Array
(
[0] => First Name
[1] => Last Name
[2] => Roll No
)
[1] => Array
(
[0] => Ram
[1] => Patel
[2] => 1
)
[2] => Array
(
[0] => Rajuv
[1] => Roy
[2] => 2
)
[3] => Array
(
[0] => Sunny
[1] => Deol
[2] => 5
)
[4] => Array
(
[0] => Akshya
[1] => Kumar
[2] => 6
)
[5] => Array
(
[0] => Amir Khan
[1] => 7
[2] =>
)
[6] => Array
(
[0] => Salman
[1] => Khan
[2] => 9
)
[7] => Array
(
[0] => Bobby
[1] => Deol
[2] => 10
)
)
)
The File I am testing is example.csv
First Name,Last Name, Roll No
Ram,Patel,1
Rajuv,Roy,2
,,
Sunny,Deol,5
Akshya,Kumar,6
Amir Khan,7
,,
Salman,Khan,9
Bobby,Deol,10,
Barun,Dhawan,11
,,
Virat,Kohli,13
Rohit,Sharma,14
How I Return all data of $qryy it's return me only last record. How I need return all off data.
public function get_subcategory(){
$qry = $this->db->get("shopping_category");
foreach($qry->result() as $row){
$this->db->where("c_id",$row->id);
$qryy = $this->db->get("shopping_subcategory");
}
return $qryy;
}
You can try this
public function get_subcategory() {
$result = [];
$qry = $this->db->get("shopping_category");
foreach ($qry->result() as $row) {
$this->db->where("c_id", $row->id);
$qryy = $this->db->get("shopping_subcategory");
$result[] = $qryy;
}
return $result;
}
The reason you get the last record is, every time you loop data through foreach it keeps replacing $qryy = $this->db->get("shopping_subcategory");
to fix this you can simply change $qryy into an array $qryy[] like this.
To improve your query. you can simply try
$qryy = [];
$this->db->select("shopping_subcategory.*");
$this->db->from("shopping_category");
$this->db->join('shopping_subcategory', 'shopping_category.id = shopping_subcategory.c_id');
$sql= $this->db->get();
$qryy = $sql->result_array();
$data['category'] = $qryy;
$this->load->view('view_name', $data);
In view
$category will show your data
I think it solve your problem. would you mind if you give it a try?
since you want from table shopping_category is only id i try to fetch it so it's not a heavy duty on your server.
$result = [];
$qry = $this->db->select("id")->get('shopping_category');
foreach ($qry->result() as $row) {
$this->db->where("c_id", $row->id);
$qryy = $this->db->get("shopping_subcategory")->result();
$result[] = $qryy;
}
return $result;
Hope that helps :)
you should use another approach to resolve your problem: use joins to query the database only once:
$this->db->join("shopping_subcategory t2","t2.c_id=t1.id");
$qry = $this->db->get("shopping_category t1");
return $qry->result();
if you output above with print_r($qry->result()), you get similar to below:
Array
(
[0] => stdClass Object
(
[ID] => 1
[company_ID] => 1
[name] => aaa
)
[1] => stdClass Object
(
[ID] => 2
[company_ID] => 1
[name] => bbb
)
[2] => stdClass Object
(
[ID] => 4
[company_ID] => 2
[name] => ccc
)
)
to resolve your approach: you need to make $qryy an array, to store each subquery data, right now you are overwriting the variable $qryy with each loop and therefore only get the last result:
$qry = $this->db->get("shopping_category");
$qryy=array();
foreach($qry->result() as $i=>$row){
$this->db->where("c_id",$row->id);
$qryy[$i] = $this->db->get("shopping_subcategory")->result();
}
return $qryy;
if you output above with print_r($qryy), you get similar to below:
Array
(
[0] => Array
(
[0] => stdClass Object
(
[ID] => 1
[company_ID] => 1
[name] => aaa
)
[1] => stdClass Object
(
[ID] => 2
[company_ID] => 1
[name] => bbb
)
)
[1] => Array
(
[0] => stdClass Object
(
[ID] => 4
[company_ID] => 2
[name] => ccc
)
)
)
therefore, depending which approach you use, you'll need to take care of your data output differently.
helpful info on joins here
im doing a lazy loading with WP_Query Pagination
it's working fine but the content duplicate itself when it reaches it's end
and when i search for a specific result it shows the result correctly
but after that it still want to do lazy load so it load random data
here is my code
lazy-load.php
<?php
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
function load_posts_by_ajax_callback(){
// check_ajax_referer( 'load_more_posts', 'security' );
$paged = $_POST['page'];
$args = array(
'post_type' => 'unit',
'post_status' => 'publish',
'posts_per_page' => 4,
'paged' => $paged
);
if ( !empty($_POST['taxonomy']) && !empty($_POST['term_id']) ){
$args['tax_query'] = array (
array(
'taxonomy' => $_POST['taxonomy'],
'terms' => $_POST['term_id'],
),
);
}
if ( ! is_null($_POST['offer']) ) {
$args['meta_query'][] = array(
'key' => 'WAKEB_hot',
'value' => '1',
'compare' => '=',
);
}
if ( ! is_null($_POST['purpose']) ) {
$args['meta_query'][] = array(
'key' => 'WAKEB_vacation',
'value' => '1',
'compare' => '=',
);
}
if (!empty($_POST['project'])){
$args['meta_query'] = array (
array(
'key' => 'WAKEB_project',
'value' => $_POST['project'],
'compare' => '='
),
);
}
// start buffer
ob_start();
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while($query->have_posts()){ $query->the_post();
get_template_part("template-parts/units");
}
endif; wp_reset_postdata();
// start buffered data in data variable
$data = ob_get_clean();
wp_send_json_success( $data );
wp_die();
}
add_action('wp_ajax_nopriv_load_projects_by_ajax', 'load_projects_by_ajax_callback');
add_action('wp_ajax_load_projects_by_ajax', 'load_projects_by_ajax_callback');
function load_projects_by_ajax_callback(){
// check_ajax_referer( 'load_more_posts', 'security' );
$paged = $_POST['page'];
$args = array(
'post_type' => 'project',
'post_status' => 'publish',
'posts_per_page' => 4,
'paged' => $paged
);
if ( ! is_null($_POST['ptype']) ) {
$args['tax_query'] = array (
array(
'taxonomy' => 'pptypes',
'field' => 'slug',
'terms' => $_POST['ptype'],
),
);
}
if ( !empty($_POST['taxonomy']) && !empty($_POST['term_id']) ){
$args['tax_query'] = array (
array(
'taxonomy' => $_POST['taxonomy'],
'terms' => $_POST['term_id'],
),
);
}
// start buffer
ob_start();
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while($query->have_posts()){ $query->the_post();
get_template_part("template-parts/projects");
}
endif; wp_reset_postdata();
// start buffered data in data variable
$data = ob_get_clean();
wp_send_json_success( $data );
wp_die();
}
lazy-load.js
$('.unit-terms li a').each( function() {
if ( this.href == window.location.href ) {
$(this).parent().addClass('current');
}
});
main.js
(function($){
$('.isotope a').on('click', function(){
$('.isotope .active').removeClass('active');
$(this).addClass('active');
var filter = $(this).data('filter');
if(filter=='*'){
$('.property').show();
}else{
$('.property').not(filter).hide();
$('.property'+filter).show();
}
return false;
});
})(jQuery);
so how can i make it work? i don't know what im doing wrong here
Here is the repo link for the full project
https://github.com/Ov3rControl/hoomerz
ok, now I understand what you meant ;) During lazy load you send to backend only page number without current state of filters and / or search string. So it sends all posttype items based on page number only. You should send also current state of filters
main.js: add this to your after-page-load function:
var currentUrl = new URL(window.location.href);
var searchQuery = urlObj.searchParams.get("k");
lazy-load.js: add search param to data posted to backend
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'search: searchQuery // new field
};
lazy-load.php: add search param to WP_Query
if ( isset($_POST['search']) && !empty($_POST['search']) ){ // new section
$args['s'] = sanitize_text_field($_POST['search']);
}
That's example for text search filter. For all filters you must
1. match every filter from front (URL get param) (main.js)
2. than put it in data object sent to backend (lazy-load.js)
3. address this variable in lazy-load.php in if(isset($_POST['param-name'])) section ( new or existing one as there are some )
I suggest to try without ob_start() / ob_get_clean(). Also if you generate html instead of raw data structure, I would simply print it to output without wp_send_json_success().
Other solution would be sending raw data (1. array in php, 2. json_encode(), 3. wp_send_json() ) and than processing in javascript (dynamic dom element creation after request to backend made).
I need to validate user thumbnail size and type when user upload their thumbnail. But I don't know how to validate array data. So please help me
p/s: I use Cakephp 2.x
my data:
Array
(
[User] => Array
(
[id] => 45
[username] => pa7264
[password] => admin
[new_password] =>
[thumbnail] => Array
(
[name] => demo.jpg
[type] => image/jpeg
[tmp_name] => D:\OpenServer\userdata\temp\phpD2FD.tmp
[error] => 0
[size] => 13582
)
)
)
You need a custom validation in a pair with getimagesize() function.
Here is a quick draft for you:
//in User.php model
public $validate = array(
'thumbnail' => array(
'imageSize' => array(
'rule' => array('check_image_size'),
'message' => 'Thumbnail size is too big!'
)
)
);
// this is custom validaion function
public function check_image_size($data)
{
$imagesize = getimagesize($data['thumbnail']['tmp_name']);
if (($imagesize[0] > 600) || ($imagesize[1] > 400)){
//here we taking request data to erase image to avoid problems in view
$request = Router::getRequest();
unset($request->data['User']['thumbnail']);
return false; //validaion failed
}
return true; //validaion passed
}
I am attempting to access the result set from a model query in the view. I have the following:
Controller:
$courseId = $this->session->userdata('courseId');
//echo "Course: ".$courseId;
if(isset($courseId) && $courseId != '')
{
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
}
Model:
function loadBasicDetailsEdit($courseId)
{
$this->db->select('*');
$this->db->where('course_id', $courseId);
$this->db->from('course');
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
return $query->result();
} else {
return FALSE;
}
}
and in the view I tried to print_r() and got this:
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
I tried to access this using $basicCourseDetails->title or $basicCourseDetails['title']
but neither are working. Any hint as to why this is happening?
Regards,
try this:
foreach($basicCourseDetails as $basic){
echo($basic->title);
}
or something like this:
echo($basicCourseDetails[0]->title);
This is an array of objects
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
Contains one stdObject in the array, so, first objects is 0, if there were more, then second item could have index 1 and so on. To retrieve data from the first (here is only one) stdobject you may use
echo $basicCourseDetails[0]->title; // title will be printed
You can send data to the view page by this line of code which is mentioned in above question.
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
But when you will access these data in view then you need to access all data one by one by using foreachloop in the view page.
For example if you have a view page like basic_details.php inside course folder then you need to write code like this to access these data.
foreach ($basicCourseDetails as $key => $value) {
$name = $value->name;
}
The above foreachloop can be written in view page where you want to access data.