I'm trying to do searches with the API from last.fm with Zend_Rest_Client.
What am I to do with the response? How do I get the values from the response?
object(Zend_Rest_Client_Result)[226]
protected '_sxml' =>
object(SimpleXMLElement)[228]
public '#attributes' =>
array
'status' => string 'ok' (length=2)
public 'results' =>
object(SimpleXMLElement)[229]
public '#attributes' =>
array
...
public 'trackmatches' =>
object(SimpleXMLElement)[230]
...
protected '_errstr' => null
How do I loop over trackmatches? Everything I try returns null.
$results = $object->getIterator();
foreach($result as $result) {
...
}
Above code will do the magic.
You have to keep dereferencing until you get to something that isn't a SimpleXMLElement object. Trying to print a SimpleXMLElement object doesn't work.
$results = $object->getIterator();
foreach($results->results->trackmatches as $t) {
echo $t->sometagname;
}
I did not manage to be able to do it with Zend. Looks like a useless class like Zend_Http. I had to use the gool 'ol SPL:
$url = $this->host . '?method=track.search';
$url .= '&api_key=' . $this->apikey;
$url .= '&track=' . urlencode($value);
try {
$xmlstr = file_get_contents($url);
$xml = new SimpleXMLElement($xmlstr);
//var_dump($xml->results->trackmatches);
return $xml->results->trackmatches;
} catch (Exception $e) {
echo '<h4>url = ' . $url . '</h4>';
var_dump($e);
}
Related
I have created a custom page on which all available courses are displayed. I have also uploaded the image for the course and now want to show the name of the course along with the image. I am able to get the names of courses from the database but how to get the image.
Try something like this
// Create a course_in_list object to use the get_course_overviewfiles() method.
require_once($CFG->libdir . '/coursecatlib.php');
$course = new course_in_list($courseid);
$outputimage = '';
foreach ($course->get_course_overviewfiles() as $file) {
if ($file->is_valid_image()) {
$imagepath = '/' . $file->get_contextid() .
'/' . $file->get_component() .
'/' . $file->get_filearea() .
$file->get_filepath() .
$file->get_filename();
$imageurl = file_encode_url($CFG->wwwroot . '/pluginfile.php', $imagepath,
false);
$outputimage = html_writer::tag('div',
html_writer::empty_tag('img', array('src' => $imageurl)),
array('class' => 'courseimage'));
// Use the first image found.
break;
}
}
echo $outputimage;
You may get course image directly from 'overviewfiles' files area.
function get_course_image()
{
global $COURSE;
$url = '';
require_once( $CFG->libdir . '/filelib.php' );
$context = context_course::instance( $COURSE->id );
$fs = get_file_storage();
$files = $fs->get_area_files( $context->id, 'course', 'overviewfiles', 0 );
foreach ( $files as $f )
{
if ( $f->is_valid_image() )
{
$url = moodle_url::make_pluginfile_url( $f->get_contextid(), $f->get_component(), $f->get_filearea(), null, $f->get_filepath(), $f->get_filename(), false );
}
}
return $url;
}
I am trying to get a menu via REST and I've created a new module and rest resource plugin that allows for GET on /entity/restmenu/{menu_name}.
I can successfully return this example json using this function when I hit the URL.
public function get(EntityInterface $entity) {
$result = array();
for ($i = 0; $i < 10; $i++) {
$temp = array(
'title' => 'Test ' . $i,
'href' => '#/' . $i
);
array_push($result, $temp);
}
return new ResourceResponse(json_encode($result));
}
I cannot figure out how to load the menu based on $entity. If I hit my URL (http://dang.dev:8888/entity/restmenu/main?_format=hal_json) $entity's value is 'main' which is the machine name of the main menu.
I've tried using Drupal menu tree, but I am not having luck, and debugging this thing with only JSON responses is quite difficult.
How do I get menu item titles and paths based on the menu machine name?
EDIT
Ok, sort of figured it out.
public function get($entity) {
$menu_name = $entity;
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$renderable = \Drupal::menuTree()->build($tree);
$result = array();
foreach (end($renderable) as $key => $val) {
$temp = array(
'menu_item' => $val,
'route' => $key
);
array_push($result, $temp);
}
return new ResourceResponse(json_encode($result));
}
Right now that will output:
[
{
"menu_item":{
"is_expanded":false,
"is_collapsed":false,
"in_active_trail":false,
"attributes":"",
"title":"Home",
"url":{
},
"below":[
],
"original_link":{
}
},
"route":"standard.front_page"
},
{
"menu_item":{
"is_expanded":false,
"is_collapsed":false,
"in_active_trail":false,
"attributes":"",
"title":"Communities",
"url":{
},
"below":[
],
"original_link":{
}
},
"route":"menu_link_content:139d0413-dc50-4772-8200-bc6c92571fa7"
}
]
any idea why url or original_link are empty?
This was the correct answer:
public function get($entity) {
$menu_name = $entity;
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$result = array();
foreach ($tree as $element) {
$link = $element->link;
array_push($result, array(
'title' => $link->getTitle(),
'url' => $link->getUrlObject()->getInternalPath(),
'weight' => $link->getWeight()
)
);
}
return new ResourceResponse(json_encode($result));
}
The $user contains a CHAR datatype from the database.
My error was:
Message: Object of class CI_DB_oci8_result could not be converted to
string
This is my Code:
$this->db->select('CONSULTATION_DATE,CONSULTATION_DESC,CONSULTATION_STATUS');
$this->db->from('SCHEDULE_REQUEST');
$this->db->where("STUDENT_ID= '". $user."'");
$this->db->where("CONSULTATION_STATUS LIKE 'Accept'");
$data['status']=$this->db->get();
use this
$this->db->select('CONSULTATION_DATE,CONSULTATION_DESC,CONSULTATION_STATUS');
$this->db->from('SCHEDULE_REQUEST');
$this->db->where("STUDENT_ID= '". $user."'");
$this->db->where("CONSULTATION_STATUS LIKE 'Accept'");
$result=$this->db->get();//data store as Object Array
EDIT 01
$this->db->select('CONSULTATION_DATE,CONSULTATION_DESC,CONSULTATION_STATUS');
$this->db->from('SCHEDULE_REQUEST');
$this->db->where("STUDENT_ID= '". $user."'");
$this->db->where("CONSULTATION_STATUS LIKE 'Accept'");
$result=$this->db->get();//data store as Object Array
$data['array'] = $result;
In View
foreach ( $array as $item )
{
echo $item['table_filed'];
}
EDIT 02
In Model
public function get_data($user)
{
$query = $this->db->query("SELECT CONSULTATION_DATE,CONSULTATION_DESC,CONSULTATION_STATUS FROM schedule_request WHERE STUDENT_ID= '$user' AND CONSULTATION_STATUS LIKE 'Accept' ");
$result = $query->result_array();
return $result;
}
In Controller
$data['result'] = $this->Model_name->get_data($user);
$this->load->view("View_name",$data)
In View
foreach ($result as $item )
{
echo $item['table_filed'];
}
How do I test a GET request of a REST API with PHPUnit 4.1? I use the Slim PHP-Framework and could manage to test the response code but not the body or header.
This is what I have so far:
TestClass:
class AssetTest extends PHPUnit_Framework_TestCase
{
public function request($method, $path, $options = array())
{
// Capture STDOUT
ob_start();
// Prepare a mock environment
Environment::mock(array_merge(array(
'REQUEST_METHOD' => $method,
'PATH_INFO' => $path,
'SERVER_NAME' => 'slim-test.dev',
), $options));
$app = new \Slim\Slim();
$this->app = $app;
$this->request = $app->request();
$this->response = $app->response();
// Return STDOUT
return ob_get_clean();
}
public function get($path, $options = array()){
$this->request('GET', $path, $options);
}
public function testGetAssets(){
$this->get('/asset');
$this->assertEquals('200', $this->response->status());
}
}
If my JSON response of http://example.com/asset looks like this (Code 200):
[
{
"AssetID": "4b0be88b9e853",
"AssetStatusID": "1"
}
]
Everything is good. To get the body of response just call the
$response->getBody() and use json_decode to decode this response. To get the header call the $response->getHeaders().
In your case it will by $this->response->getBody(). So your test
method will be look like this
public function testGetAssets(){
$this->get('/asset');
$response = json_decode($this->response->getBody(), true); //response body
$headers = $this->response->getHeaders() //response headers
$this->assertEquals('200', $this->response->status());
}
This answer is respect to the latest version of guzzlehttp i.e. 6.0
I am using the following code to list all the manufacturers and it works like a charm:
$attribute = Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product', 'manufacturer');
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
$preparedManufacturers = array();
foreach($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
}
if (count($preparedManufacturers)) {
echo "<h2>Manufacturers</h2><ul>";
foreach($preparedManufacturers as $optionId => $value) {
echo "<li>" . $value . " - (" . $optionId . ")</li>";
}
echo "</ul>";
}
What I am looking for is a way to display the number of products associated with each of the manufacturers. Can someone please tell me the way of doing this?
Many thanks
Not all mine, but works for me in 1.6+?
<?php
include_once 'app/Mage.php';
Mage::app();
$attribute = Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product', 'manufacturer');
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
$preparedManufacturers = array();
foreach ($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
}
if (count($preparedManufacturers)) {
echo "<h2>Manufacturers</h2><ul>";
foreach ($preparedManufacturers as $optionId => $value) {
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addFieldToFilter(array(array('attribute' => 'manufacturer', 'eq' => $optionId)));
$mumberOfProducrt = count($collection);
echo "<li>" . $value . " - (" . $mumberOfProducrt . ")</li>";
}
echo "</ul>";
}
?>
This would work but won't be the most efficient:
foreach($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
$collection = Mage::getModel('catalog/product')->getCollection();
$collection
->addAttributeToSelect('*') // '*' not efficient though
->addAttributeToFilter('manufacturer', array('eq' => $value->getOptionId()))
//->addAttributeToFilter('manufacturer', $value->getOptionId())
;
$count = $collection->->getSize();
}
It's an extra query for each manufacturer so it's not great, if you have some caching etc it won't be too bad though.
Working code should do it
$collection = Mage::getModel('catalog/product')->getCollection()->groupByAttribute('manufacturer')
->addFieldToFilter('status',Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->addExpressionAttributeToSelect("count",'COUNT({{entity_id}})', 'entity_id');
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);