How do I put a SimplePie Enclosure Link into an Array - php

I am attempting to parse an RSS feed which uses media enclosures. I am using SimplePie and I have been able to parse it, and make all the needed elements appear on the page.
But I am writing a plugin for a CMS and I need to put those elements into an array. All are working fine, except the $item->get_enclosure().
I should say, that in the array, what is returned is a string of gibberish. I need it to return the url to the file.
Here is the relevant code:
// Get Enclosure
$enclosures = array();
$item_enclosures = $item->get_enclosures();
if ( ! empty($item_enclosures))
{
foreach ($item_enclosures as $enclosure)
{
if ($enclosure = $item->get_enclosure())
{
$enclosure->get_link();
} else {
$enclosure->get_title();
}
}
}
$items[] = array(
'item_title' => $item->get_title(),
'item_link' => $item->get_permalink(),
'item_date' => $item->get_date('U'),
'item_content' => $item->get_content(),
'item_img' => $item->get_enclosure(),
'item_description' => $item->get_description(),
'item_categories' => $categories,
'item_authors' => $authors
);
}
return $items;
Does anyone know how to make the 'item_img' return a link to the file, rather than what seems to be some kind of encoded string of characters.

From http://simplepie.org/wiki/reference/simplepie_enclosure/get_link
$link = $item->get_enclosure()->get_link();
would seem to do what you want.

Related

Array becoming multi-dimensional in AJAX request

So I am creating a function in WordPress which counts and sets a user session and storing its values in the user's local storage. I was able to make it work perfectly by using cookies and when the site is hosted locally, for some reason, it is not working when I uploaded it on the staging site. So I am trying implement this function using another approach and decided to use local storage instead.
There's a problem with the Array values that the function is generating and I have spent almost the entire day trying to debug the problem. It is generating multi-dimensional instead of a single one.
Here's my function code:
function monitor_post_views() {
$page_id = 'page' . $_POST['page_id'];
$timestamp = time();
// 30 minutes timeout
$timeout = 1800;
// Serves as my guide for debugging, will not include in the final code
$message = '';
if ( ! empty($_POST['page_id_array']) ) {
//Checks if values from local storage exist
//Gets the stored Array coming from AJAX call
$page_id_array[] = json_decode(stripslashes($_POST['page_id_array']), true);
if ( in_array_r($page_id_array, $page_id) ) {
//Check if current page is found in array
$message = 'FOUND IN ARRAY CHECKING !!!!';
$temp= [];
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array_temp;
//Pushes the generated array inside the $page_id_array
array_push($page_id_array, $temp);
print_r(json_encode($page_id_array));
foreach ( $page_id_array as $page ) {
//If page is in array, check if the session is expired, if not, do nothing, if expired, update and then run the view function
}
} else {
// ID Not found in Array, Insert a new entry
$message = 'ID NOT FOUND IN ARRAY, CREATING ENTRY !!!';
$temp = [];
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array_temp;
//Pushes the generated array inside the $page_id_array
array_push($page_id_array, $temp);
print_r(json_encode($page_id_array));
//Set post view function here base on $_POST['page_id']
}
} else {
//Not found in local storage, need to create one
$message = 'CREATING A NEW ENTRY !!!!';
$temp = [];
$page_id_array = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array;
print_r(json_encode($temp));
//Set post view function here base on $_POST['page_id']
}
wp_die();
}
add_action('wp_ajax_monitor_post_views', 'monitor_post_views');
add_action('wp_ajax_nopriv_monitor_post_views', 'monitor_post_views');
Here's a screenshot of what this function generates
Array
Here's a sample JSON
[[{"id":"page1202","expiration":1551125579,"message":"FOUND IN ARRAY CHECKING !!!!"},{"id":"page1206","expiration":1551125613,"message":"ID NOT FOUND IN ARRAY !!!! INSERTING ENTRY !!!"}],{"id":"page1296","expiration":1551125624,"message":"ID NOT FOUND IN ARRAY !!!! INSERTING ENTRY !!!"}]
I was trying to generate a one dimensional but ended up with this.
Any thoughts? Thanks in advance
The problem is you are creating arrays too many times:
Change $page_id_array and $page_id_array_temp to
$page_id_array=new \stdClass();//no need to declare as an array
replace
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
with
$page_id_array->id=$page_id;
$page_id_array->expiration=$timestamp;
$page_id_array->message=$message;
also change
$temp = [];
you can use it directly
//no need to declare $temp as an array
$temp=$page_id_array;

What's the right way of getting category list of a Wordpress web site using PHP?

I need to read the list of Wordpress categories of a blog and insert them as hyperlinks into my PHP Page.
I used simplexml_load_file and it's working on my local Wamp Server perfectly.
But I'm worried about performance of the production server with a lot of users. Should I do caching for production page? How? Is there another standard solution for this?
$feed_url = "http://my.web.site/category/$category/feed/";
// If there is some errors, return empty
if(! $news_xml = #simplexml_load_file($feed_url, 'SimpleXMLElement', LIBXML_NOCDATA & LIBXML_NOWARNING & LIBXML_NOERROR))
{
log_message('error','Feed load error: '.$feed_url);
return [];
}
$data = [];
foreach ($news_xml->channel->item as $news_item) {
$new_item = [
"title" => (string)$news_item->title,
"link" => (string)$news_item->link,
"comments" => (string)$news_item->comments,
"pubDate" => (string)$news_item->pubDate,
"category" => (string)$news_item->category,
"guid" => (string)$news_item->guid,
"description" => (string)$news_item->description,
];
if ($news_item->children('media', true)->content) {
$new_item["image_url"] = (string)$news_item->children('media', true)->content->attributes()->url;
}
$data[] = $new_item;
}

connection between android app and cakephp

Hi I'm making a web service in cakephp for an android app. I am getting the request and the respose is being send but the response is not visible on the client's end. My code is as shown below. Can there be some other method to send the response.
public function AndroidApp() {
if (isset($_POST["myHttpData"])) {
$coupon = trim($_POST["myHttpData"]);
$couponId = $this->Code->find('all', array(
'conditions' => array(
'Code.coupon_code' => $coupon,
'Code.status' => 'Used'
),
'fields' => array('Code.id')));
$studentAssessmentId = $this->StudentAssessment->find('all', array(
'conditions' => array(
'StudentAssessment.code_id' => $couponId[0]['Code']['id'],
'StudentAssessment.status' => 'Complete'
),
'fields' => array('StudentAssessment.id')));
$scores = $this->AssessmentScore->find('all', array(
'conditions' => array(
'AssessmentScore.student_assessment_id' => $studentAssessmentId[0]['StudentAssessment']['id']
),
'fields' => array('AssessmentScore.score')));
$json = array();
$assessment_data = array();
//debug($scores);
$i = 0;
foreach ($scores as $score) {
$assessment_data[$i] = array("score" => $score['AssessmentScore']['score']);
$i+=1;
}
header('Content-type: application/json');
$json['success'] = $assessment_data;
$android = json_encode($json);
} else {
$json['error'] = "Sorry, no score is available for this coupon code!";
$android = json_encode($json);
}
echo $android;
code smell, non-cakephp standards
First of all, as mentioned in comments by others, you're not using the CakePHP request/response objects. Because of this, you're overly complicating things. See the documentation here;
http://book.cakephp.org/2.0/en/controllers/request-response.html
http://book.cakephp.org/2.0/en/controllers/request-response.html#dealing-with-content-types
And
http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
The $scores loop to reformat the query results is probably redundant if you replace the find('all') with find('list'), using 'score' as display field. See the documentation here http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list
bugs
There also seems to be some bugs in your code;
the content-type header is only sent if $_POST["myHttpData"] is present.
you're only checking if $_POST["myHttpData"] is present, not if it actually contains any data (empty)
you're not checking if the various queries return a result. This will cause errors in your code if a query did not return anything! For example, you assume that $couponId[0]['Code']['id'] is present (but it won't be if the coupon-code was not found)
possible answer
Apart from these issues, the most probable cause for your problem is that you did not disable 'autoRender'. Therefore CakePHP will also render the view after you've output your JSON, causing a malformed JSON response.
public function AndroidApp() {
$this->autoRender = false;
// rest of your code here
}

Scrape page and separate internal from external links

Building a little PHP scraper , I'm writing a little function which should separate my Internal & External links,
I'm passing the function a copy of the html source code along with the base host address
$source = file_get_contents('http://www.example.com');
$host = "mysite.com";
here is my function so far...
function find_page_links($source, $host){
if($source){
$htmlDoc = new DomDocument();
#$htmlDoc->loadhtml($source);
$int_links = array();
$ext_links = array();
// GET LINKS
foreach($htmlDoc->getElementsByTagName('a') as $link) {
$url = trim($link->getAttribute('href'));
$title = trim($link->getAttribute('title'));
$text = trim($link->nodeValue);
$rel = trim($link->getAttribute('rel'));
$pos = strpos($url,$host);
if( $pos === false ){ // NO MATCH EXTERNAL
if( (substr($url, 0, 1) == '/') ||
(substr($url, 0, 1) == '#') )
{
// INTERNAL
$int_links[] = array( 'link_url' => $url,
'link_text' => $text,
'link_title' => $title,
'link_rel' => $rel
);
}else{
// EXTERNAL
$ext_links[] = array( 'link_url' => $url,
'link_text' => $text,
'link_title' => $title,
'link_rel' => $rel
);
}
}else{
if( $pos < 20 ){
// INTERNAL
$int_links[] = array( 'link_url' => $url,
'link_text' => $text,
'link_title' => $title,
'link_rel' => $rel );
}else{
// EXTERNAL
$ext_links[] = array( 'link_url' => $url,
'link_text' => $text,
'link_title' => $title,
'link_rel' => $rel
);
}
} // end else
} // end foreach
$content = array();
$content['int_links'] = $int_links;
$content['ext_links'] = $ext_links;
return $content ;
}
}
So whats happening is the function loads the HTML via DomDocument
I create 2 arrays to store both internal & external
Loop through the document and getElementsByTagName('a')
It then uses strpos to check if the host address "example.com" is within the link URL if there is NO match/false then it's external, but we do a further check to make sure the link URL doesnt start with a forward slash ie: "/contact-us.php" that would mean its an internal, also in that check we check for a "#" tag at the begining which would be an anchor link on the page...
so that was IF pos === false / no match
now If host is in the link URL its a match, I do another check to see if the position of the host is lower down in the string, which would be internal ie:
http://example.com/about/
but if the position is greater than 20 (just a number plucked from the air) then..
like a google plus link or facebook link the host url will be present in the link but much further along the string which would mean its an external,
ie: http://www.facebook.com/plugins/like.php?href=http://example.com/
phew...
if you guys have any other BETTER ways to spot an external or internal link please let me know..my results, really vary depending on the site, if links are using the full path,

Easiest method to save external rss feeds

I have big problem, I want to read rss feeds from mydealz.de and save their titles, contents and dates to my db. I'm using cakephp, is there any easy way to do it? I'm simply out of ideas
I was trying to do that from this tutorial : http://www.google.com/url?sa=D&q=http://blog.loadsys.com/2009/06/19/cakephp-rss-feed-datasource/&usg=AFQjCNFhFxVyjqEFoPFfZgt-X2NYpmv0OQ but in model I delclared that I'm not using database.
App::import('Core', 'HttpSocket');
$HttpSocket = new HttpSocket();
$input = $HttpSocket->get('http://www.example.com/something.xml');
App::import('Xml');
$xml = new Xml($input);
$xmlAsArray = $xml->toArray();
foreach($xmlAsArray as $item) {
$this->Article->create();
$data['Article'] = array(
'title' => $item['title'],
'contents' => $item['contents'],
'date' => $item['date']
);
$this->Article->save($data);
}

Categories