Yahoo Answers API解析

时间:2014-02-23 04:29:51

标签: php api parsing yahoo yahoo-api

所以我已经正确运行并且看起来像这样。

<?php
/**
 * @package Yahoo Answer
 * @author The HungryCoder
 * @link http://hungrycoder.xenexbd.com/?p=953
 * @version 1.0
 * @license GPL, This class does not come with any expressed or implied warranties! Use at your own risks!  
 */

class yahooAnswer{
    var $appID;
    var $searchQuestionURL = 'http://answers.yahooapis.com/AnswersService/V1/questionSearch?';
    var $getQuestionURL = 'http://answers.yahooapis.com/AnswersService/V1/getQuestion?';

    private $numResults = 10;
    private $numStart = 0;

    function  __construct($appid) {

        $this->appID=$appid;
    }

    function set_numResults($num_results){
        $this->numResults = $num_results;
    }

    /**
     * Search for questions for the given keywords. Returned results can be associative array or XML
     * @param <string> $kewyord
     * @return <string> Returns the results set either in XML format or associative array. 
     */

    function search_questions($params){
        if(!is_array($params)){
            throw new Exception('The parameters must be an array!');
        }
        $defaults = array(
            'search_in'     =>  '',
            'category_name' =>  '',
            'date_range'    =>  '', //7, 7-30, 30-60, 60-90, more90
            'sort'          =>  'relevance', //relevance, date_desc, date_asc
            'type'          =>  'all',
            'output'        =>  'php',
            'results'       =>  $this->numResults,
            'start'         =>  $this->numStart,
            'region'        =>  'us',
            'appid'         =>  $this->appID,
        );
        $params = array_merge($defaults,$params);

        if(!$params['appid']){
            throw new Exception('APP ID is empty!', 404);
        }
        if(!$params['query']) {
            throw new Exception('Query is not set!', '404');
        }

        $req_params = $this->array2query_string($params);

        $url = $this->searchQuestionURL.$req_params;
        $results = $this->make_call($url);
        if($params['output']=='php'){
            $results = unserialize($results);
            return $results['Questions'];
        }

        return $results;

    }


    /**
     * Get all answers of a given question ID
     * @param <array> $params keys are: question_id, output, appid
     * @return <string> Returns all answers in expected format. default format is php array
     */

    function get_question($params){

         if(!is_array($params)){
            throw new Exception('The parameter must be an array!');
        }
        $defaults = array(
            'question_id'   =>  '',
            'output'        =>  'php',
            'appid'         =>  $this->appID,
        );
        $params = array_merge($defaults,$params);



        if(!$params['appid']){
            throw new Exception('APP ID is empty!', 404);
        }
        if(!$params['question_id']) {
            throw new Exception('Question ID is not set!', '404');
        }


        $req_params = $this->array2query_string($params);


        $url = $this->getQuestionURL.$req_params;
        $results = $this->make_call($url);
        if($params['output']=='php'){
            $results = unserialize($results);
            return $results['Questions'][0];
        }
        return $results;
    }



    protected function make_call($url){
        if(function_exists('curl_init')){
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
            curl_setopt($ch, CURLOPT_TIMEOUT,60);

            $result = curl_exec($ch);
            curl_close($ch);
            return $result;
        } else if(function_exists('file_get_contents')) {
            return file_get_contents($url);
        } else {
            throw new Exception('No method available to contact remote server! We must need cURL or file_get_contents()!', '500');
        }
    }

    protected  function array2query_string($array){
        if(!is_array($array)) throw new Exception('Parameter must be an array', '500');
        $params ='';
        foreach($array as $key=>$val){
            $params .= "$key=$val&";
        }
        return $params;
    }
}


$appid = 'myID';
$params = array(
    'query'     =>      'yoga',   //enter your keyword here. this will be searched on yahoo answer
    'results'   =>      10,         //number of questions it should return
    'type'      =>      'resolved',  //only resolved questiosn will be returned. other values can be all, open, undecided
    'output'    =>      'php',      //result will be PHP array. Other values can be xml, json, rss
);
$query  = 'yoga'; //enter your keyword here to search for
$yn = new yahooAnswer($appid);
//search questions
try{
    $questions = $yn->search_questions($params);
} catch (Exception $e){
    echo ($e->getMessage());
}


foreach ($questions as $question) {
    //now get the answers for the question_id;
    try{
        $answers = $yn->get_question(array('question_id'=>$question['id']));
        echo '<pre>';
        print_r($answers);
        echo '<pre>';
    } catch (Exception $e){
        echo($e->getMessage());
    }

}

?>

但是当它输出时,我会得到类似......

    Array
(
[id] => 20061129192938AAW1tcY
[type] => Answered
[Subject] => what is yoga?
[Content] => what is yoga and how do you do it what are some exercises

[Date] => 2006-11-29 19:29:38
[Timestamp] => 1164828578
[Link] => http://answers.yahoo.com/question/?qid=20061129192938AAW1tcY
[Category] => Array
    (
        [id] => 396545382
        [content] => Diet & Fitness
    )

[UserId] => 688e0eb3c85d1a580a06aa9eb8a35da5aa
[UserNick] => Tess M
[UserPhotoURL] => http://l.yimg.com/sc/28231/answers1/images/a/i/identity/nopic_48.png
[NumAnswers] => 8
[NumComments] => 0
[ChosenAnswer] => (m)

Yoga, in general, is a spiritual practice or discipline that helps the individual unify his/her body, mind, and heart.   

Yoga is a direct experience of the vast interrelatedness of all life and of all things. You will feel at peace at the end of a yoga class because there is a natural realignment of your body which leads to a natural realignment of your perception of life and of who you are.

You will need to develop discipline and there is hard work involved especially when you first begin.

Hatha Yoga is the study and practice of physical alignments and breath.

Yoga is much more that postural alignment and breathing.

If you stay with yoga long enough, you may discover a "spiritual awakening" (for lack of a better phrase.) You will find out that who you are, is not just your body, and not just the conversations in your mind. 

Through steady practice, you will manifest less self-importance, less material attachment, more capacity for joy, less judgmentalness, and more tolerance toward others.

Yoga is about transformation, not hamstrings, but along the way we have to take care of them.  This is not dogma, but a direct experience. Yoga will open your eyes to things you have not experienced before. It will take you beyond the mundane survival level and into a whole new appreciation of life.

Genuine yoga will change your life, your habits, your body, your health, your mind, your breathing patterns, your attitudes, your outlook. Yoga is about learning from direct experience. You will develop wisdom of how your body works most efficiently. You will learn how your conscious and unconsious mind can either support or harm you, and then later, a deeper wisodm naturally gets revealed.  The benefits of Yoga will come to those who practice.

There are many types of Yoga. That which comes to mind first is Hatha Yoga an element of Raja yoga, yoga that deals mainly with physical postures and breathing. Karma Yoga emphasizes spiritual practice to help the individual unify body, mind, and heart through certain practices in one’s daily life and work. Bhakti Yoga, a devotional form, generally encompasses chanting, reading of scriptures and worship practices. In general, Yoga is any practice that can turn the practitioner inward to find and experience an individual’s spiritual essence, to realize or awaken to his/her spiritual nature. Another type of yoga is jnana yoga.

Each posture, or asana, is held for a period of time and synchronised with the breath. Generally, a yoga session begins with gentle asanas and works up to the more vigorous or challenging postures. A full yoga session should exercise every part of the body and should include pranayama (breath control practices), relaxation and meditation. The different postures or asanas include:

Lying postures 
Sitting postures 
Standing postures 
Forward bends 
Twisting postures 
Back bending postures 
Inverted, or upside down postures.


There is no competition in Yoga, everyone is different.
[ChosenAnswererId] => AA10589847
[ChosenAnswererNick] => mallimalar_2000
[ChosenAnswerTimestamp] => 1164829754
[ChosenAnswerAwardTimestamp] => 1165000022
[Answers] => Array
    (
        [0] => Array
            (
                [Content] => Here's a site that might help you get started
                [Reference] => 
                [Best] => 
                [UserId] => af05b0ac8e18e5786d6c9e466a234d4caa
                [UserNick] => jennytkd13
                [Date] => 2006-11-29 19:32:23
                [Timestamp] => 1164828743
            )

我试图只获取每个帖子的UserNick字段,我似乎无法得到它。我只能把它缩小到一个帖子。 这里的任何帮助将非常感谢!

0 个答案:

没有答案