简体   繁体   English

从PHP对象数组中获取单个值

[英]Get single value from PHP object array

I am very new to PHP and I want to grab a single value from the OpenGraph object and print it. 我是PHP的新手,我想从OpenGraph对象中获取一个值并打印它。 Not sure what I am doing wrong? 不确定我做错了什么? I keep getting "Array" as the print out. 我一直把“数组”作为打印输出。

class OpenGraph implements Iterator{

public static $TYPES = array(
    'activity' => array('activity', 'sport'),
    'business' => array('bar', 'company', 'cafe', 'hotel', 'restaurant'),
    'group' => array('cause', 'sports_league', 'sports_team'),
    'organization' => array('band', 'government', 'non_profit', 'school', 'university'),
    'person' => array('actor', 'athlete', 'author', 'director', 'musician', 'politician', 'public_figure'),
    'place' => array('city', 'country', 'landmark', 'state_province'),
    'product' => array('album', 'book', 'drink', 'food', 'game', 'movie', 'product', 'song', 'tv_show'),
    'website' => array('blog', 'website'),
);

private $_values = array();

static public function fetch($URI) {
    $curl = curl_init($URI);
    curl_setopt($curl, CURLOPT_FAILONERROR, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 15);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    $response = curl_exec($curl);
    curl_close($curl);
    if (!empty($response)) {
        return self::_parse($response);
    } else {
        return false;
    }
}

static private function _parse($HTML) {
    $old_libxml_error = libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML($HTML);

    libxml_use_internal_errors($old_libxml_error);
    $tags = $doc->getElementsByTagName('meta');
    if (!$tags || $tags->length === 0) {
        return false;
    }
    $page = new self();
    $nonOgDescription = null;

    foreach ($tags AS $tag) {
        if ($tag->hasAttribute('property') &&
            strpos($tag->getAttribute('property'), 'og:') === 0) {
            $key = strtr(substr($tag->getAttribute('property'), 3), '-', '_');
            $page->_values[$key] = $tag->getAttribute('content');
        }

        //Added this if loop to retrieve description values from sites like the New York Times who have malformed it. 
        if ($tag ->hasAttribute('value') && $tag->hasAttribute('property') &&
            strpos($tag->getAttribute('property'), 'og:') === 0) {
            $key = strtr(substr($tag->getAttribute('property'), 3), '-', '_');
            $page->_values[$key] = $tag->getAttribute('value');
        }
        //Based on modifications at https://github.com/bashofmann/opengraph/blob/master/src/OpenGraph/OpenGraph.php
        if ($tag->hasAttribute('name') && $tag->getAttribute('name') === 'description') {
            $nonOgDescription = $tag->getAttribute('content');
        }

    }
    //Based on modifications at https://github.com/bashofmann/opengraph/blob/master/src/OpenGraph/OpenGraph.php
    if (!isset($page->_values['title'])) {
        $titles = $doc->getElementsByTagName('title');
        if ($titles->length > 0) {
            $page->_values['title'] = $titles->item(0)->textContent;
        }
    }
    if (!isset($page->_values['description']) && $nonOgDescription) {
        $page->_values['description'] = $nonOgDescription;
    }
    //Fallback to use image_src if ogp::image isn't set.
    if (!isset($page->values['image'])) {
        $domxpath = new DOMXPath($doc);
        $elements = $domxpath->query("//link[@rel='image_src']");
        if ($elements->length > 0) {
            $domattr = $elements->item(0)->attributes->getNamedItem('href');
            if ($domattr) {
                $page->_values['image'] = $domattr->value;
                $page->_values['image_src'] = $domattr->value;
            }
        }
    }
    if (empty($page->_values)) { return false; }

    return $page;
}

public function __get($key) {
    if (array_key_exists($key, $this->_values)) {
        return $this->_values[$key];
    }

    if ($key === 'schema') {
        foreach (self::$TYPES AS $schema => $types) {
            if (array_search($this->_values['type'], $types)) {
                return $schema;
            }
        }
    }
}

public function keys() {
    return array_keys($this->_values);
}

public function __isset($key) {
    return array_key_exists($key, $this->_values);
}

public function hasLocation() {
    if (array_key_exists('latitude', $this->_values) && array_key_exists('longitude', $this->_values)) {
        return true;
    }

    $address_keys = array('street_address', 'locality', 'region', 'postal_code', 'country_name');
    $valid_address = true;
    foreach ($address_keys AS $key) {
        $valid_address = ($valid_address && array_key_exists($key, $this->_values));
    }
    return $valid_address;
}

private $_position = 0;
public function rewind() { reset($this->_values); $this->_position = 0; }
public function current() { return current($this->_values); }
public function key() { return key($this->_values); }
public function next() { next($this->_values); ++$this->_position; }
public function valid() { return $this->_position < sizeof($this->_values); }}

Implementation: 执行:

require_once('OpenGraph.php');
$graph = OpenGraph::fetch('http://www.google.com');
echo $graph->keys('description');

I actually got this code from a github here: https://github.com/scottmac/opengraph 我实际上从github这里得到了这个代码: https//github.com/scottmac/opengraph

The keys() method returns an array, and it takes no arguments. keys()方法返回一个数组,它不带参数。 What you are doing when you use 你用的时候在做什么

echo $graph->keys('description')

is calling that method with 'description' as an argument, which it will ignore, then echoing the entire array. 用“description”作为参数调用该方法,它将忽略它,然后回显整个数组。 When you use echo on an array, it will just print Array like you are seeing. 当你在数组上使用echo时,它只会像你看到的那样打印Array Because of the __get() magic method , I think you should be able to just use 由于__get() 魔术方法 ,我认为你应该能够使用

echo $graph->description

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM