Foursquare - 如何使用菜单URL中的file_get_contents获取菜单

时间:2014-07-28 09:52:08

标签: php html xpath domdocument

我无法使用foursquare API获取特定场地ID的所有菜单。所以我选择了另一种方法来使用下面的菜单URL中的'file_get_contents'来获取菜单详细信息。

https://foursquare.com/v/mr-teriyaki-burlingame-ca/4b269e61f964a5206f7e24e3/menu

代码:

$menus  =    file_get_contents("https://foursquare.com/v/mr-teriyaki-burlingame-ca/4b269e61f964a5206f7e24e3/menu");
preg_match_all('/<div class="menu">(.*)<\/div><div>/ims',$menus,$menuDetails);
echo "<pre>";print_r($menuDetails[1][0]);echo "</pre>";

任何人都可以提供如何从菜单名称和菜单价格等菜单细节构建多维数组的解决方案。

谢谢,

Arularasan D。

1 个答案:

答案 0 :(得分:1)

或者你可以在{:1}上使用DOMDocument

$url = 'https://foursquare.com/v/mr-teriyaki-burlingame-ca/4b269e61f964a5206f7e24e3/menu';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec($ch);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$sections = $xpath->query('//div[@class="section"]'); // get the main section
// this is the div where it holds all the menu's
$menu = array();

// so every/each item inside the menu
foreach($sections as $section) {

    $title = '';
    // first get the title section (Appetizers, etc.)
    $title_node = $xpath->query('.//div[@class="sectionHeader"]/div[@class="contents"]/text()', $section);
    if($title_node->length == 1) { // if this does exist
        $title = $title_node->item(0)->nodeValue; // get the node value  
    } else {
        continue; // else there no reason to linger here, skip
    }

    $items = array();
    // get the 2nd column
    // the name of the food and its price
    $items_node = $xpath->query('.//div[2]/div[@class="entry"]/div[@class="menuHeader"]', $section);
    if($items_node->length > 0) {
        foreach($items_node as $item) {
            if($xpath->query('.//div[@class="price"]', $item)->length > 0) {
                $items[] = array(
                    'title' => $xpath->query('.//span[@class="title"]', $item)->item(0)->nodeValue,
                    'price' => $xpath->query('.//div[@class="price"]', $item)->item(0)->nodeValue,
                );
            }
        }
    }

    // after gathering values in each row (the title and the rows of each item), put the inside an array
    $menu[] = array('title' => $title, 'items' => $items);
}

echo '<pre>';
print_r($menu);

应打印如下内容:

Array
(
    [0] => Array
    (
        [title] => Appetizer‌
        [items] => Array
            (
                [0] => Array
                    (
                        [title] => Edamame Boiled Soy Beans
                        [price] => 3.95
                    )

                [1] => Array
                    (
                        [title] => Fried Oyster
                        [price] => 6.95
                    )

                [2] => Array
                    (
                        [title] => Fried Scallop
                        [price] => 6.95
                    )