I am trying to format from a simpleXML object, but its returning:
title1title2title3
Even though this is...
return ''.$title.'';
Here's my whole code.
<?php
class ForumFeed {
private function getXMLFeeds($feed = 'all')
{
/*
Fetch the XML feeds
*/
$globalFeedXML = file_get_contents('/forum/syndication.php?limit=3');
$newsFeedXML = file_get_contents('/forum/syndication.php?fid=4&limit=3');
/*
Turn feed objects
*/
$globalFeed = new SimpleXMLElement($globalFeedXML);
$newsFeed = new SimpleXMLElement($newsFeedXML);
/*
Return requested feed
*/
if ($feed == 'news') {
return $newsFeed;
} else if ($feed == 'all') {
return $globalFeed;
} else {
return false;
}
}
private function formatFeeds($feed, $node)
{
/*
Format Feeds for displayable content..
*/
$getFeedObject = $this->getXMLFeeds($feed);
$feedData = $getFeedObject->xpath('channel/item/'.$node);
while (list( , $node) = each($feedData)) {
echo $node;
}
}
public function feed($feed)
{
$title = $this->formatFeeds($feed, 'title');
$url = $this->formatFeeds($feed, 'url');
return ''.$title.'';
}
}
$feeds = new ForumFeed();
echo $feeds->feed('all');
I'm not sure what I'm doing wrong.
The problem is in this function:
private function formatFeeds($feed, $node)
{
/*
Format Feeds for displayable content..
*/
$getFeedObject = $this->getXMLFeeds($feed);
$feedData = $getFeedObject->xpath('channel/item/'.$node);
while (list( , $node) = each($feedData)) {
echo $node;
}
}
It's echoing $node, rather than returning anything to the caller. Try something like this:
private function formatFeeds($feed, $node)
{
/*
Format Feeds for displayable content..
*/
$getFeedObject = $this->getXMLFeeds($feed);
$feedData = $getFeedObject->xpath('channel/item/'.$node);
$result = array();
while (list( , $node) = each($feedData)) {
$result[] = $node;
}
return implode(', ', $result);
}
Related
Excuse my English, please.
I use Rollingcurl to crawl various pages.
Rollingcurl: https://github.com/LionsAd/rolling-curl
My class:
<?php
class Imdb
{
private $release;
public function __construct()
{
$this->release = "";
}
// SEARCH
public static function most_popular($response, $info)
{
$doc = new DOMDocument();
libxml_use_internal_errors(true); //disable libxml errors
if (!empty($response)) {
//if any html is actually returned
$doc->loadHTML($response);
libxml_clear_errors(); //remove errors for yucky html
$xpath = new DOMXPath($doc);
//get all the h2's with an id
$row = $xpath->query("//div[contains(#class, 'lister-item-image') and contains(#class, 'float-left')]/a/#href");
$nexts = $xpath->query("//a[contains(#class, 'lister-page-next') and contains(#class, 'next-page')]");
$names = $xpath->query('//img[#class="loadlate"]');
// NEXT URL - ONE TIME
$Count = 0;
$next_url = "";
foreach ($nexts as $next) {
$Count++;
if ($Count == 1) {
/*echo "Next URL: " . $next->getAttribute('href') . "<br/>";*/
$next_link = $next->getAttribute('href');
}
}
// RELEASE NAME
$rls_name = "";
foreach ($names as $name) {
$rls_name .= $name->getAttribute('alt');
}
// IMDB TT0000000 RLEASE
if ($row->length > 0) {
$link = "";
foreach ($row as $row) {
$tt_info .= #get_match('/tt\\d{7}/is', $doc->saveHtml($row), 0);
}
}
}
$array = array(
$next_link,
$rls_name,
$tt_info,
);
return ($array);
}
}
Output/Return:
$array = array(
$next_link,
$rls_name,
$tt_info,
);
return ($array);
Call:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function get_match($regex, $content, $pos = 1)
{
/* do your job */
preg_match($regex, $content, $matches);
/* return our result */
return $matches[intval($pos)];
}
require "RollingCurl.php";
require "imdb_class.php";
$imdb = new Imdb;
if (isset($_GET['action']) || isset($_POST['action'])) {
$action = (isset($_GET['action'])) ? $_GET['action'] : $_POST['action'];
} else {
$action = "";
}
echo " 2222<br /><br />";
if ($action == "most_popular") {
$popular = '&num_votes=1000,&production_status=released&groups=top_1000&sort=moviemeter,asc&count=40&start=1';
if (isset($_GET['date'])) {
$link = "https://www.imdb.com/search/title?title_type=feature,tv_movie&release_date=,".$_GET['date'].$popular;
} else {
$link = "https://www.imdb.com/search/title?title_type=feature,tv_movie&release_date=,2018".$popular;
}
$urls = array($link);
$rc = new RollingCurl([$imdb, 'most_popular']); //[$imdb, 'most_popular']
$rc->window_size = 20;
foreach ($urls as $url) {
$request = new RollingCurlRequest($url);
$rc->add($request);
}
$stream = $rc->execute();
}
If I output everything as "echo" in the class, everything is also displayed. However, I want to call everything individually.
If I now try to output it like this, it doesn't work.
$stream[0]
$stream[1]
$stream[3]
Does anyone have any idea how this might work?
Thank you very much in advance.
RollingCurl doesn't do anything with the return value of the callback, and doesn't return it to the caller. $rc->execute() just returns true when there's a callback function. If you want to save anything, you need to do it in the callback function itself.
You should make most_popular a non-static function, and give it a property $results that you initialize to [] in the constructor.. Then it can do:
$this->results[] = $array;
After you do
$rc->execute();
you can do:
foreach ($imdb->results as $result) {
echo "Release name: $result[1]<br>TT Info: $result[2]<br>";
}
It would be better if you put the data you extracted from the document in arrays rather than concatenated strings, e.g.
$this->$rls_names = [];
foreach ($names as $name) {
$this->$rls_names[] = $name->getAttribute('alt');
}
$this->$tt_infos = [];
foreach ($rows as $row) {
$this->$tt_infos[] = #get_match('/tt\\d{7}/is', $doc->saveHtml($row), 0);
}
$this->next_link = $next[0]->getAttribute('href'); // no need for a loop to get the first element of an array
I have a result array from query in a controller, like :
[...]controller/Admin.php :
public function user_email()
{
$this->db->select('user_email');
$this->db->from('user');
$query = $this->db->get();
$data['email'] = $query->result_array();
$this->template->render('admin/user_driver', $data, 'admin');
}
The libraries/Template.php :
class Template {
protected $ci;
public $data;
public function __construct()
{
$this->ci =& get_instance();
}
public function render($view, $viewdata = null, $template = 'frontend')
{
$html = $this->ci->load->view($view, $viewdata, TRUE);
$this->data['template'] = $this->parse_blocks($html);
$this->data['_viewdata'] = $viewdata;
$this->ci->load->view("template/{$template}", $this->data);
}
public function parse_blocks($html)
{
$blocks = array();
if(empty($html)) $html = " ";
libxml_disable_entity_loader(false);
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_use_internal_errors(false);
libxml_disable_entity_loader(true);
foreach ($dom->getElementsByTagName('template') as $node) {
$section = $node -> getAttribute('block');
$blocks[$section] = $this->DOMinnerHTML($node);
}
return $blocks;
}
private function DOMinnerHTML(DOMNode $element)
{
$innerHTML = "";
$children = $element->childNodes;
foreach ($children as $child)
{
$innerHTML .= $element->ownerDocument->saveHTML($child);
}
return $innerHTML;
}
public function block_exists($blockname = NULL)
{
if(empty($blockname))
return false;
return (is_array($this->data) && is_array($this->data['template']) && array_key_exists($blockname,$this->data['template']));
}
}
I var_dump($email) in my user_driver.php view, but it throws Undefined variable: email. The file user_driver.php is under [...]views/admin/user_driver.php.
What did I do wrong?
Your result from the Database is currently returning as a multi-dimensional array result. Change this to row if you're expecting just one result:
$data['email'] = $query->row_array();
This will provide you with a single dimensional array to fetch from:
$this->db->select('user_email');
$this->db->from('user');
$query = $this->db->get();
$dbresult = $query->row_array();
$emailAddress = $dbresult["user_email"];
$data['email'] = $emailAddress;
I have created rest api for getting categories and sub-categories using recursion technique. Here is my code:-
public function getNodeChildrenData(Varien_Data_Tree_Node $node)
{
$data = array(
'title' => $node->getData('name'),
'url' => $node->getData('url_key'),
);
foreach ($node->getChildren() as $childNode) {
if (!array_key_exists('children', $data)) {
$data['children'] = array();
}
$data['children'][$childNode->getData('entity_id')] = $this->getNodeChildrenData($childNode);
}
return $data;
}
public function getCategoryTree($recursionLevel, $storeId = 1)
{
$parent = Mage::app()->getStore()->getRootCategoryId();
$tree = Mage::getResourceModel('catalog/category_tree');
/* #var $tree Mage_Catalog_Model_Resource_Category_Tree */
$nodes = $tree->loadNode($parent)
->loadChildren($recursionLevel)
->getChildren();
$tree->addCollectionData(null, false, $parent);
$categoryTreeData = array();
foreach ($nodes as $node) {
$categoryTreeData[$node->getData('entity_id')] = $this->getNodeChildrenData($node);
}
return $categoryTreeData;
}
public function _retrieveCollection()
{
$cur_category = array();
$cur_category[] = $this->getCategoryTree(2);
return json_encode($cur_category);
}
The result which I am getting is in the following format:-
"[{
\"1\": {
\"title\":\"Root Catalog\",\"url\":null,\"children\":{
\"2\":{
\"title\":\"Electronics\",\"url\":null, \"children\":{
\"3\":{\"title\":\"Laptops\",\"url\":\"laptops\"}
}
},
\"4\":{
\"title\":\"Men\",\"url\":\"apparels\",\"children\":{
\"9\":{\"title\":\"Formal Mens Jeans\",\"url\":\"formal-mens-jeans\"}
}
},
\"5\":{\"title\":\"Women\",\"url\":\"women\"},
\"6\":{\"title\":\"Baby & Kids\",\"url\":\"baby-kids\"},
\"7\":{\"title\":\"Home & Furniture\",\"url\":\"home-furniture\"}
}
}
}]"
Can you please tell me where I am getting wrong.
i want to fetch titles and title's tags.
public function titles()
{
$query=mysql_query("SELECT * FROM title");
while($row = mysql_fetch_object($query)){
$data->title[] = $row;
$data->tag[] = $this->tags($row->id);
}
return $data;
}
public function tags($title_id)
{
$query=mysql_query("SELECT * FROM tag WHERE title_id = '$title_id'");
while($row = mysql_fetch_object($query)){
$tag[] = $row;
}
return $tag;
}
I'm trying to print in this way
$data = titles();
foreach($data->title as $title)
{
echo $title->topic;
foreach($data->tag as $tag)
{
echo $tag->name;
}
}
but it doesnt work. How can I do?
thank you for help.
You should have something like this in your titles method
$data = new stdClass();
$data->title = array();
$data->tag = array();
You also need to add files like this
$data->title[$row->id][] = $row;
$data->tag[$row->id][] = $this->tags($row->id);
Then you can loop like this
foreach($data->title as $id => $title)
{
echo $title->topic;
foreach($data->tag[$id] as $tag)
{
echo $tag->name;
}
}
Also Enable error so that you can see PHP Errors .. at on top of your page
error_reporting(E_ALL);
ini_set("display_errors","On");
PHP DOC ON mysql_***
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include
What i think your code should look like
class Somthing {
private $db;
function __construct() {
$this->db = new mysqli("localhost", "user", "password", "db");
}
function titles() {
$data = new stdClass();
$data->title = array();
$data->tag = array();
$result = $this->db->query("SELECT * FROM title");
while ( $row = $result->fetch_object() ) {
$data->title[$row->id] = $row;
$data->tag[$row->id] = $this->tags($row->id);
}
return $data;
}
function tags($title_id) {
$tag = array();
$result = $this->db->query("SELECT * FROM tag WHERE title_id = '$title_id'");
while ( $row = $result->fetch_object() ) {
$tag[] = $row;
}
return $tag;
}
}
$somthing = new Somthing();
foreach ($somthing->titles() as $id => $title ) {
echo $title->topic;
foreach ( $data->tag[$id] as $tag ) {
echo $tag->name;
}
}
I'm using drupal's NAT module and need to get the nid from the term id.
Here's what I tried:
foreach ( (array)nat_get_nids($termid) as $natid ) {
$NatName = $natid->name;
}
print $natid;
This does not work.
Node auto term's get nid function is like this:
function nat_get_nids($tids, $get_nodes = FALSE) {
static $nid_cache = NULL;
static $node_cache = NULL;
$return = array();
// Keep processing to a minimum for empty tid arrays.
if (!empty($tids)) {
// Sort tid array to ensure that the cache_string never suffers from order
// issues.
sort($tids);
$cache_string = implode('+', $tids);
if ($get_nodes) {
if (isset($node_cache[$cache_string])) {
return $node_cache[$cache_string];
}
elseif (isset($nid_cache[$cache_string])) {
// If the nid cache stores the same string, node_load() each nid and
// return them.
$return = array();
foreach (array_keys($nid_cache[$cache_string]) as $nid) {
$return[$nid] = node_load($nid);
}
$node_cache[$cache_string] = $return;
return $return;
}
}
else {
if (isset($nid_cache[$cache_string])) {
return $nid_cache[$cache_string];
}
elseif (isset($node_cache[$cache_string])) {
// If the node cache stores the same string, retrieve only the nids and
// return them.
foreach ($node_cache[$cache_string] as $nid => $node) {
$return[$nid] = $node->name;
}
// Cache extracted results.
$nid_cache[$cache_string] = $return;
return $return;
}
}
// Results have not been cached.
$tids = implode(', ', $tids);
$result = db_query("SELECT n.nid, t.name FROM {nat} n INNER JOIN {term_data} t USING (tid) WHERE n.tid IN (". db_placeholders($tids) .")", $tids);
while ($node = db_fetch_object($result)) {
if ($get_nodes) {
$return[$node->nid] = node_load($node->nid);
}
else {
$return[$node->nid] = $node->name;
}
}
if ($get_nodes) {
$node_cache[$cache_string] = $return;
}
else {
$nid_cache[$cache_string] = $return;
}
}
return $return;
}
Thanks in advance!
Edit: Try based on the first answer:
foreach (nat_get_nids($termid) as $nid => $node_name) {
}
print $node_name;
It looks like nat_get_nids is returning an associative array, so your for loop should look like
foreach (nat_get_nids($termid) as $nid => $node_name) {
...
}
$nids = nat_get_nids(array($termid));