function createSpots() { // TODO :: Some caching ?? $this->pq = $pq = new phpQuery(); $this->dom = $dom = $pq->newDocument($this->owner->template->template_source); if (!$this->owner instanceof \Frontend) { $pq->pq($dom)->attr('xepan-page-content', 'true'); $pq->pq($dom)->addClass('xepan-page-content'); } foreach ($dom['.xepan-component'] as $d) { $d = $pq->pq($d); if (!$d->hasClass('xepan-serverside-component')) { continue; } $i = $this->spots++; $inner_html = $d->html(); $with_spot = '{' . $this->owner->template->name . '_' . $i . '}' . $inner_html . '{/}'; $d->html($with_spot); } $content = $this->updateBaseHrefForTemplates(); $content = str_replace('<!--xEpan-ATK-Header-Start', '', $content); $content = str_replace('xEpan-ATK-Header-End-->', '', $content); $this->owner->template->loadTemplateFromString($content); $this->owner->template->trySet($this->app->page . '_active', 'active'); }
function init() { parent::init(); if (!$this->api->auth->isLoggedIn()) { $this->js()->univ()->errorMessage('You Are Not Logged In')->execute(); } if ($_POST['length'] != strlen($_POST['body_html'])) { $this->js()->univ()->successMessage('Length send ' . $_POST['length'] . " AND Length calculated again is " . strlen($_POST['body_html']))->execute(); } if ($_POST['crc32'] != sprintf("%u", crc32($_POST['body_html']))) { $this->js()->univ()->successMessage('CRC send ' . $_POST['crc32'] . " AND CRC calculated again is " . sprintf("%u", crc32($_POST['body_html'])))->execute(); } try { $content = $_POST['body_html']; include_once getcwd() . '/lib/phpQuery.php'; $pq = new \phpQuery(); $doc =& $pq->newDocument(trim($content)); // include_once getcwd().'/lib/phpQuery.php'; // $doc = \phpQuery::newDocument( $content ); $server = $doc['[data-is-serverside-component=true]']; foreach ($doc['[data-is-serverside-component=true]'] as $ssc) { $pq->pq($ssc)->html("")->append($html); } $content = $doc->htmlOuter(); $this->api->current_page['content'] = urldecode(trim($content)); $this->api->current_page['body_attributes'] = urldecode($_POST['body_attributes']); $this->api->exec_plugins('epan-page-before-save', $this->api->current_page); $this->api->current_page->save(); $this->api->exec_plugins('epan-page-after-save', $this->api->current_page); if ($_POST['take_snapshot'] == 'Y') { // $this->api->exec_plugins('epan-page-before-snapshot',$this->api->current_page); $new_version = $this->api->current_page->ref('EpanPageSnapshots'); $new_version['title'] = $this->api->current_page['title']; $new_version['keywords'] = $this->api->current_page['keywords']; $new_version['description'] = $this->api->current_page['description']; $new_version['body_attributes'] = $this->api->current_page['body_attributes']; $new_version['content'] = $this->api->current_page['content']; $new_version->save(); // $this->api->exec_plugins('epan-page-after-snapshot',$this->api->current_page); } } catch (Exception_StopInit $e) { } catch (Exception $e) { throw $e; $this->js()->univ()->errorMessage('Error... Could not save your page ' . $e->getMEssage())->excute(); exit; } echo "saved"; exit; }
public static function hyphenate($strBuffer) { global $objPage; $arrSkipPages = \Config::get('hyphenator_skipPages'); if (is_array($arrSkipPages) && in_array($objPage->id, $arrSkipPages)) { return $strBuffer; } $o = new \Org\Heigl\Hyphenator\Options(); $o->setHyphen(\Config::get('hyphenator_hyphen'))->setDefaultLocale(static::getLocaleFromLanguage($objPage->language))->setRightMin(\Config::get('hyphenator_rightMin'))->setLeftMin(\Config::get('hyphenator_leftMin'))->setWordMin(\Config::get('hyphenator_wordMin'))->setFilters(\Config::get('hyphenator_filter'))->setQuality(\Config::get('hyphenator_quality'))->setTokenizers(\Config::get('hyphenator_tokenizers')); $h = new \Org\Heigl\Hyphenator\Hyphenator(); $h->setOptions($o); $doc = \phpQuery::newDocumentHTML($strBuffer); foreach (pq('body')->find(\Config::get('hyphenator_tags')) as $n => $item) { $strText = pq($item)->html(); // ignore html tags, otherwise ­ will be added to links for example if ($strText != strip_tags($strText)) { continue; } $strText = str_replace('­', '', $strText); // remove manual ­ html entities before $strText = $h->hyphenate($strText); if (is_array($strText)) { $strText = current($strText); } pq($item)->html($strText); } return $doc->htmlOuter(); }
function search_query($kw) { $wf = new Workflows(); $url = 'http://www.bilibili.tv/search?keyword=' . urlencode($kw) . '&orderby=&formsubmit='; $content = $wf->request($url, array(CURLOPT_ENCODING => 1)); $doc = phpQuery::newDocumentHTML($content); $list = $doc->find('li.l'); $i = 0; foreach ($list as $item) { $link = pq($item)->children('a:first')->attr('href'); if (strpos($link, 'http') !== 0) { $link = 'http://www.bilibili.tv' . $link; } $info = pq($item)->find('div.info > i'); $author = pq($item)->find('a.upper:first')->text(); $view = $info->eq(0)->text(); $comment = $info->eq(1)->text(); $bullet = $info->eq(2)->text(); $save = $info->eq(3)->text(); $date = $info->eq(4)->text(); $subtitle = 'UP主:' . $author . ' 播放:' . $view . ' 评论:' . $comment . ' 弹幕:' . $bullet . ' 收藏:' . $save . ' 日期:' . $date; $wf->result($i, $link, pq($item)->find('div.t:first')->text(), $subtitle, 'icon.png', 'yes'); $i++; } if (count($wf->results()) == 0) { $wf->result('0', $url, '在bilibili.tv中搜索', $kw, 'icon.png', 'yes'); } return $wf->toxml(); }
public function finish() { phpQuery::newDocumentFileHTML($this->downloadUrl, $this->charset); $nodeCount = pq("#list2")->count(); $articleList = pq("#list2 tr"); echo "Start\n"; for ($i = 0; $i < $this->loop; $i++) { echo '='; } echo "\n"; $i = 0; foreach ($articleList as $tr) { $i++; if ($i <= 1) { # Filter the first node which has no meaning. continue; } $className = $tr->nodeValue; # This class order and its name. $classNameCombine = explode(' ', $className); $j = 0; $this->content[$i - 1]['chapterName'] = ''; foreach ($classNameCombine as $k => $v) { # Put all class order and its name into $this->content array. $v = trim($v); if (empty($v)) { continue; } $j++; if ($j == 1) { $this->content[$i - 1]['chapterId'] = $v; } else { $this->content[$i - 1]['chapterName'] .= $v . " "; } } $child = pq("td", $tr)->html(); $trueContent = explode(' ', $child); $linkString = ''; foreach ($trueContent as $k => $v) { $v = trim($v); if (empty($v)) { continue; } if ($v == "<a") { $linkString = $v . ' ' . $trueContent[$k + 1]; break; } } $urls = explode("\"", $linkString); $this->content[$i - 1]['link'] = $urls[1]; // $name = explode("<", $urls[2]); // $name = substr($name[0], 1); // $this->content[$i-1]['name'] = $name; } var_dump($this->content); for ($i = 0; $i < $this->loop; $i++) { echo '='; } echo "\nFinished! \n"; }
function getAllSubCategories($filename) { $categories = unserialize(file_get_contents($filename)); echo "---- run getAllSubCategories() ----\n\r"; foreach ($categories as $j => $category) { if ($category['childrens']) { foreach ($category['childrens'] as $k => $children) { echo "---- crawling childrens for {$children['name']} ----\n\r"; $doc = phpQuery::newDocumentHTML(fetch('http://www.walmart.com' . $children['link'])); phpQuery::selectDocument($doc); foreach (pq('.shop-by-category li') as $el) { echo "---- " . pq($el)->find('a')->attr('href') . "} ----\n\r"; $childrens[] = array('name' => pq($el)->find('a')->data('name'), 'link' => pq($el)->find('a')->attr('href')); } $categories[$j]['childrens'][$k]['childrens'] = $childrens; } } } echo "---- creating deparment file ----\n\r"; $file = fopen($filename, 'w+'); echo "---- writing deparment file ----\n\r"; fputs($file, serialize($categories)); echo "---- closing deparment file ----\n\r"; fclose($file); }
public function first_image($htmldata) { $pq = phpQuery::newDocumentHTML($htmldata); $img = $pq->find('img:first'); $src = $img->attr('src'); return $src; }
public function parse_archive(Archive $archive) { if ($archive->cover_mode) { return [$this->get_image_by_cover($archive->cover)]; } $result = curl($archive->url, curl_options($this->domain)); $archivePQ = \phpQuery::newDocumentHTML($result['data']); $content = $archivePQ['#content']; $title = $content['.entry-title']->html(); $imgs = $content['.entry-content']->html(); if (preg_match_all('#' . $this->domain . 'wp-content/[^"]*#', $imgs, $matches)) { $archive->images = array_merge(array_unique($matches[0])); } if (!$archive->images) { $title = $content['.main-title']->html(); $imgs = $content['.main-body']->html(); if (preg_match_all('#<a[^>]+href="(' . $this->domain . 'wp-content/[^"]*)">#', $imgs, $matches)) { $archive->images = array_merge(array_unique($matches[1])); } } if (strtolower($this->charset) != strtolower($GLOBALS['app_config']['charset'])) { $archive->title = iconv(strtoupper($this->charset), strtoupper($GLOBALS['app_config']['charset']) . '//IGNORE', $title); } $archive->title = $title; }
public function find_product_url($product_name) { $url = 'http://ek.ua/'; $data = array('search_' => $product_name); $response = Request::factory($url)->query($data)->execute(); //echo Debug::vars($response->body()); //echo Debug::vars($response->headers()); $response = $response->body(); try { $doc = phpQuery::newDocument($response); } catch (Exception $ex) { $errors[] = $ex->getMessage(); echo Debug::vars($errors); } if (!isset($errors)) { /* Нужно взять заголовок и найти в нем слово найдено */ /* * что я заметил, удивительно но на разных машинах этот заголовои идет с разным классом * на данный момент этот класс oth */ $str = $doc->find('h1.oth')->html(); if (preg_match('/найдено/', $str)) { echo Debug::vars('алилуя !!!'); die; } return $str; } }
/** * Query the response for a JQuery compatible CSS selector * * @link https://code.google.com/p/phpquery/wiki/Selectors * @param $selector string * @return phpQueryObject */ public function queryHTML($selector) { if (is_null($this->pq)) { $this->pq = phpQuery::newDocument($this->content); } return $this->pq->find($selector); }
function theContent($content) { $doc = phpQuery::newDocumentHTML($content); phpQuery::selectDocument($doc); foreach (pq('a') as $link) { $linkurl = pq($link)->attr('href'); $linkHostname = $this->getUrlHostname($linkurl); if ($linkHostname != FALSE) { if (!in_array($linkHostname, $this->blockedDomains)) { $linkHash = md5($linkurl); $query = "SELECT * FROM {$this->tableBitlyExternal} WHERE id='{$linkHash}'LIMIT 1;"; $linkData = $this->db->get_row($query, ARRAY_A); if (empty($linkData)) { $bitly = new Bitly($this->bitlyUsername, $this->bitlyApikey); $shortURL = $bitly->shorten($linkurl); $shortURLData = get_object_vars($bitly->getData()); if (!empty($shortURLData)) { $linkData = array('id' => $linkHash, 'url' => $linkurl, 'short_url' => $shortURLData['shortUrl'], 'hash' => $shortURLData['userHash'], 'created' => current_time('mysql')); $this->db->insert($this->tableBitlyExternal, $linkData); } } if (!empty($linkData)) { pq($link)->attr('href', $linkData['short_url']); } } } } return $doc->htmlOuter(); }
public function getLinkContent() { require_once './ThinkPHP/Library/Vendor/Collection/phpQuery.php'; $link = op_t(I('post.url')); $content = get_content_by_url($link); $charset = preg_match("/<meta.+?charset=[^\\w]?([-\\w]+)/i", $content, $temp) ? strtolower($temp[1]) : "utf-8"; \phpQuery::$defaultCharset = $charset; \phpQuery::newDocument($content); $title = pq("meta[name='title']")->attr('content'); if (empty($title)) { $title = pq("title")->html(); } $title = iconv($charset, "UTF-8", $title); $keywords = pq("meta[name='keywords'],meta[name='Keywords']")->attr('content'); $description = pq("meta[name='description'],meta[name='Description']")->attr('content'); $url = parse_url($link); $img = pq("img")->eq(0)->attr('src'); if (is_bool(strpos($img, 'http://'))) { $img = 'http://' . $url['host'] . $img; } $title = text($title); $description = text($description); $keywords = text($keywords); $return['title'] = $title; $return['img'] = $img; $return['description'] = empty($description) ? $title : $description; $return['keywords'] = empty($keywords) ? $title : $keywords; exit(json_encode($return)); }
public function addclass($html, $selector, $class) { require __DIR__ . '/phpQuery.php'; $pq = \phpQuery::newDocument($html); $pq[$selector]->addClass($class); return new \Twig_Markup($pq, 'UTF-8'); }
/** * ___render___ * * @method ___render___ * @param {string} $content */ protected function ___render___($content) { if ($content && is_string($content)) { if ($this->functions_for_render && (is_array($this->functions_for_render) || $this->functions_for_render instanceof ArrayObject)) { $before = $this->cache_read === true ? array() : array_filter((array) $this->functions_for_render, create_function('$v', 'return $v[\'after_cache\'] !== true;')); $after = array_filter((array) $this->functions_for_render, create_function('$v', 'return $v[\'after_cache\'] === true;')); } else { $before = $after = array(); } if (0 < count($before) || 0 < count($after)) { $pq = phpQuery::newDocument($content); //before cache foreach ($before as $fn) { $pq = call_user_func($fn, $pq); } if ($this->cache_file && !$this->cache_read) { file_put_contents($this->cache_file, $pq); } //after cache foreach ($before as $fn) { $pq = call_user_func($fn, $pq); } $content = $pq; } else { if ($this->cache_file) { file_put_contents($this->cache_file, $content); } } } echo $content; }
public function go() { require_once $_SERVER["DOCUMENT_ROOT"] . "/classes/XML.php"; $xml = file_get_contents("http://alfabank.by/a-blog.xml"); $rss = new \XML($xml); foreach ($rss->rss->channel->item as $it) { $dom = \phpQuery::newDocumentHTML($it->childByName("content:encoded")); $date = date_create($it->pubDate->getData()); $arResult = array( "IBLOCK_ID" => self::ABLOG_IBLOCK_ID, "NAME" => $it->title->getData(), "DATE_ACTIVE_FROM" => date_format($date, 'd.m.Y'), "PREVIEW_TEXT" => $it->description->getData(), "PREVIEW_PICTURE" => \CFile::MakeFileArray($dom->find('img')->attr('src')), "DETAIL_TEXT" => $it->childByName("content:encoded"), "CODE" => \Ns\Bitrix\Helper::Create('iblock')->useVariant('text')->translite($it->title->getData()), "PROPERTY_VALUES" => array("ORIGINAL_LINK" => $it->link->getData()) ); $this->objElement->Add($arResult); if ($this->objElement->LAST_ERROR) { prentExpection($this->objElement->LAST_ERROR); } } return true; }
public function test_data() { $this->prepareLookup(); $this->preparePages(); $access = AccessTable::byTableName('dropdowns', 'test1'); $data = $access->getData(); $this->assertEquals('["1","[\\"title1\\",\\"This is a title\\"]"]', $data[0]->getValue()); $this->assertEquals('["1","title1"]', $data[1]->getValue()); $this->assertEquals('John', $data[2]->getValue()); $this->assertEquals('1', $data[0]->getRawValue()); $this->assertEquals('1', $data[1]->getRawValue()); $this->assertEquals('John', $data[2]->getRawValue()); $this->assertEquals('This is a title', $data[0]->getDisplayValue()); $this->assertEquals('title1', $data[1]->getDisplayValue()); $this->assertEquals('John', $data[2]->getDisplayValue()); $R = new \Doku_Renderer_xhtml(); $data[0]->render($R, 'xhtml'); $pq = \phpQuery::newDocument($R->doc); $this->assertEquals('This is a title', $pq->find('a')->text()); $this->assertContains('title1', $pq->find('a')->attr('href')); $R = new \Doku_Renderer_xhtml(); $data[1]->render($R, 'xhtml'); $pq = \phpQuery::newDocument($R->doc); $this->assertEquals('title1', $pq->find('a')->text()); $this->assertContains('title1', $pq->find('a')->attr('href')); $R = new \Doku_Renderer_xhtml(); $data[2]->render($R, 'xhtml'); $this->assertEquals('John', $R->doc); }
public function addBackendAdminMenu($strBuffer, $strTemplate) { if ($strTemplate != 'be_main' || !\BackendUser::getInstance()->isAdmin) { return $strBuffer; } // replace the scripts before processing -> https://code.google.com/archive/p/phpquery/issues/212 $arrScripts = StringUtil::replaceScripts($strBuffer); $objDoc = \phpQuery::newDocumentHTML($arrScripts['content']); $objMenu = new BackendTemplate($this->strTemplate); $arrActions = array(); $arrActiveActions = deserialize(\Config::get('backendAdminMenuActiveActions'), true); foreach (empty($arrActiveActions) ? array_keys(\Config::get('backendAdminMenuActions')) : $arrActiveActions as $strAction) { $arrActionData = $GLOBALS['TL_CONFIG']['backendAdminMenuActions'][$strAction]; $objAction = new BackendTemplate($this->strEntryTemplate); $objAction->setData($arrActionData); // href = callback? if (is_array($arrActionData['href']) || is_callable($arrActionData['href'])) { $strClass = $arrActionData['href'][0]; $strMethod = $arrActionData['href'][1]; $objInstance = \Controller::importStatic($strClass); $objAction->href = $objInstance->{$strMethod}(); } $objAction->class = $strAction; $arrActions[] = $objAction->parse(); } $objMenu->actions = $arrActions; $objDoc['#tmenu']->prepend($objMenu->parse()); $strBuffer = StringUtil::unreplaceScripts($objDoc->htmlOuter(), $arrScripts['scripts']); // avoid double escapings introduced by phpquery :-( $strBuffer = preg_replace('@&([^;]{2,4};)@i', '&$1', $strBuffer); return $strBuffer; }
function start_el(&$output, $object, $depth = 0, $args = array(), $current_object_id = 0) { // append next menu element to $output parent::start_el($output, $object, $depth, $args, $current_object_id); // now let's add a custom form field if (!class_exists('phpQuery')) { // load phpQuery at the last moment, to minimise chance of conflicts (ok, it's probably a bit too defensive) require_once 'phpQuery-onefile.php'; } $_doc = phpQuery::newDocumentHTML($output); $_li = phpQuery::pq('li.menu-item:last'); // ":last" is important, because $output will contain all the menu elements before current element // if the last <li>'s id attribute doesn't match $item->ID something is very wrong, don't do anything // just a safety, should never happen... $menu_item_id = str_replace('menu-item-', '', $_li->attr('id')); if ($menu_item_id != $object->ID) { return; } // fetch previously saved meta for the post (menu_item is just a post type) $curr_bg = esc_attr(get_post_meta($menu_item_id, 'snpshpwp_menu_item_bg', TRUE)); $curr_bg_pos = esc_attr(get_post_meta($menu_item_id, 'snpshpwp_menu_item_bg_pos', TRUE)); $curr_upldr = '<span class="button media_upload_button" id="snpshpwp_upload_' . $menu_item_id . '">' . __('Upload', 'snpshpwp') . '</span>'; // by means of phpQuery magic, inject a new input field $_li->find('a.item-delete')->before("\n\t\t\t\t\t<p class='snpshpwp_menu_item_bg description description-thin'>\n\t\t\t\t\t<label for='snpshpwp_menu_item_bg_{$menu_item_id}'>" . __('Background image', 'snpshpwp') . "<br/>\n\t\t\t\t\t<input type='text' value='{$curr_bg}' name='snpshpwp_menu_item_bg_{$menu_item_id}' /><br/>\n\t\t\t\t\t</label>\n\t\t\t\t\t{$curr_upldr}\n\t\t\t\t\t</p>\n\t\t\t\t\t<p class='snpshpwp_menu_item_bg_pos description description-thin'>\n\t\t\t\t\t<label for='snpshpwp_menu_item_bg_{$menu_item_id}'>" . __('Background orientation', 'snpshpwp') . "<br/>\n\t\t\t\t\t<select name='snpshpwp_menu_item_bg_pos_{$menu_item_id}'>\n\t\t\t\t\t\t<option value='left-landscape'" . ($curr_bg_pos == 'left-landscape' ? ' selected' : '') . ">" . __('Left Landscape', 'snpshpwp') . "</option>\n\t\t\t\t\t\t<option value='left-portraid'" . ($curr_bg_pos == 'left-portraid' ? ' selected' : '') . ">" . __('Left Portraid', 'snpshpwp') . "</option>\n\t\t\t\t\t\t<option value='right-landscape'" . ($curr_bg_pos == 'right-landscape' ? ' selected' : '') . ">" . __('Right Landscape', 'snpshpwp') . "</option>\n\t\t\t\t\t\t<option value='right-portraid'" . ($curr_bg_pos == 'right-portraid' ? ' selected' : '') . ">" . __('Right Portraid', 'snpshpwp') . "</option>\n\t\t\t\t\t\t<option value='pattern-repeat'" . ($curr_bg_pos == 'pattern-repeat' ? ' selected' : '') . ">" . __('Pattern', 'snpshpwp') . "</option>\n\t\t\t\t\t\t<option value='framed-full'" . ($curr_bg_pos == 'framed-full' ? ' selected' : '') . ">" . __('Framed', 'snpshpwp') . "</option>\n\t\t\t\t\t</select>\n\t\t\t\t\t</label>\n\t\t\t\t\t</p>\n\t\t\t\t\t"); // swap the $output $output = $_doc->html(); }
function testShowData() { $handler = new Doku_Handler(); $xhtml = new Doku_Renderer_xhtml(); $plugin = new syntax_plugin_data_entry(); $result = $plugin->handle($this->exampleEntry, 0, 10, $handler); $plugin->_showData($result, $xhtml); $doc = phpQuery::newDocument($xhtml->doc); $this->assertEquals(1, pq('div.inline.dataplugin_entry.projects', $doc)->length); $this->assertEquals(1, pq('dl dt.type')->length); $this->assertEquals(1, pq('dl dd.type')->length); $this->assertEquals(1, pq('dl dt.volume')->length); $this->assertEquals(1, pq('dl dd.volume')->length); $this->assertEquals(1, pq('dl dt.employee')->length); $this->assertEquals(1, pq('dl dd.employee')->length); $this->assertEquals(1, pq('dl dt.customer')->length); $this->assertEquals(1, pq('dl dd.customer')->length); $this->assertEquals(1, pq('dl dt.deadline')->length); $this->assertEquals(1, pq('dl dd.deadline')->length); $this->assertEquals(1, pq('dl dt.server')->length); $this->assertEquals(1, pq('dl dd.server')->length); $this->assertEquals(1, pq('dl dt.website')->length); $this->assertEquals(1, pq('dl dd.website')->length); $this->assertEquals(1, pq('dl dt.task')->length); $this->assertEquals(1, pq('dl dd.task')->length); $this->assertEquals(1, pq('dl dt.tests')->length); $this->assertEquals(1, pq('dl dd.tests')->length); }
public function go() { try { $this->checker = \Ns\Bitrix\Helper::Create('iblock')->useVariant('checker'); } catch (\Exception $e) { prentExpection($e->getMessage()); } foreach ($this->dom->find("table.fileinfo") as $table) { $this->arFields = array(); $this->arFields["IBLOCK_ID"] = self::ALFADOCUMENTS_IBLOCK_ID; $table = \phpQuery::pq($table); $this->arFields["NAME"] = $table->find('a:eq(1)')->text(); $this->arFields["PROPERTY_VALUES"]["LINK"] = $table->find('a:eq(1)')->attr("href"); prent($this->arFields); $this->Add(); } /** * Check and add element to infoblock Terminals */ return true; }
function real_test($idnum, $name) { error_reporting(E_ALL); ini_set('display_errors', 'On'); include './vendor/autoload.php'; //$idnum = '130123198706234534'; //$name = '祁星月'; $url = 'http://www.runchina.org.cn/portal.php?mod=score&ac=personal'; $headstr = "-H 'Pragma: no-cache' -H 'Origin: http://www.runchina.org.cn' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,ja;q=0.2' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Cache-Control: no-cache' -H 'Referer: http://www.runchina.org.cn/portal.php?mod=score&ac=personal' -H 'Cookie: SMHa_2132_saltkey=tQi19Tmq; SMHa_2132_lastvisit=1468828350; SMHa_2132_sid=l9z09Q; SMHa_2132_lastact=1468832009%09portal.php%09score; Hm_lvt_b0a502205e02e6127ae831a751ff05b3=1468831949; Hm_lpvt_b0a502205e02e6127ae831a751ff05b3=1468832009' -H 'Connection: keep-alive'"; $data = array('idnum' => $idnum, 'name' => $name); $reg = '/\'([A-Za-z]+)\\:\\s?([^\']+)\'/'; preg_match_all($reg, $headstr, $matches); $keys = $matches[1]; $values = $matches[2]; $headers = array_combine($keys, $values); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $content = curl_exec($ch); $pq = phpQuery::newDocument($content); $real_items = array(); $results = $pq->find("table tr:gt(0)"); foreach ($results as $result) { $x = $result->nodeValue; $v = explode("\n", $x); $real_items[] = array($v[0], trim($v[2]), trim($v[5]), trim($v[6])); } echo json_encode($real_items); }
static function getProducts() { $products = pq(self::$productsQuery); $productData = array(); foreach ($products->elements as $good) { $product_links[$good->textContent] = $good->getAttribute('href'); } foreach ($product_links as $sku => $link) { $html = file_get_contents(self::$srcUrl . $link); $url = parse_url($link); if (isset($url['query'])) { parse_str($url['query'], $params); $cat = isset($params['cat_id']) ? $params['cat_id'] : 0; $vendor = isset($params['vendor_id']) ? $params['vendor_id'] : 0; } phpQuery::newDocumentHTML($html, self::$encoding); $product = new stdClass(); $product->model = $sku; $product->sku = $sku; $product->name = self::getProductName(); $product->specs = self::getProductSpecs(); $product->img = self::getProductImage(); $product->cat = $cat; $product->vendor = $vendor; $productData[] = $product; } return $productData; }
public function actionKNet() { // создаем экземпляр класса $client = new Client(); // отправляем запрос к странице Яндекса $res = $client->request('GET', 'http://kondratiev.net/loader.php?getPage=gallery'); // получаем данные между открывающим и закрывающим тегами body $body = $res->getBody(); // подключаем phpQuery $document = \phpQuery::newDocumentHTML($body); // получаем список новостей //$news = $document->find("ul.b-news-list"); $kSite = $document->find(".widePhotoGallery"); //d(count($kSite)); // выполняем проход циклом по списку foreach ($kSite as $elem) { //pq аналог $ в jQuery $pq = pq($elem); // удалим первую новость в списке //$pq->find('li.list__item:first')->remove(); // выполним поиск в скиске ссылок //$tags = $pq->find('li.list__item a'); // добавим ковычки в начало и в конец предложения //$tags->append('" ')->prepend(' "'); // // добавим свой класс к последней новости списка $pq->find('div.widePhoto')->addClass('display-block'); } // вывод списка новостей яндекса с главной страницы в представление return $this->render('k-net', ['kSite' => $kSite]); }
public function get_data() { if (!class_exists('phpQuery')) { include dirname(__FILE__) . '/phpQuery.php'; } $response = wp_remote_get($this->url . '/tags'); if (is_wp_error($response)) { return false; } phpQuery::newDocument($response['body']); $version = false; $zip_url = false; foreach (pq('table.tags a.name') as $tag) { $tag = pq($tag); if (version_compare($tag->text(), $version, '>=')) { $href = $tag->attr('href'); $commit = substr($href, strrpos($href, '/') + 1); $zip_url = $this->url . '/snapshot/' . $commit . '.zip'; $version = $tag->text(); $updated_at = $tag->parent()->prev()->text(); } } $this->new_version = $version; $this->zip_url = $zip_url; $this->updated_at = date('Y-m-d', strtotime($updated_at)); $this->description = pq('div.page_footer_text')->text(); }
public function getManagerPage($errors = array()) { $html = phpQuery::newDocumentFileHTML(MVBAPK_HTML_DIR . 'admin/manager-page.html'); if ($_POST['submited']) { if (count($errors)) { $html['#notice-message > div:first']->removeClass('ui-state-highlight'); $html['#notice-message > div:first']->addClass('ui-state-error'); $html['#notice-message #message']->html(implode('<br/>', $errors)); } } else { $html['#notice-message']->addClass('dialog'); } //add list of styles $styles = $this->modelNode->getStyleList(); if (is_array($styles)) { foreach ($styles as $id => $style) { $id = esc_attr($id); $label = esc_js($style['label']); $html['#style']->append("<option value='{$id}'>{$label}</option>"); } reset($styles); $first = current($styles); $html['#current-style-display'] = $first['label']; } echo $html->htmlOuter(); }
/** * @param string $pageHtml * @param string $link * @return string */ public function detectPageType($pageHtml, $link) { require_once './vendors/phpQuery.php'; $doc = phpQuery::newDocumentHTML($pageHtml); $item = $doc->get('#fw_post_wrap'); if (preg_match("/id([0-9]+)/", $link, $matches)) { return 'user'; } if (preg_match("/wall-?([0-9_]+)/", $link, $matches)) { return 'wall'; } if (preg_match("/public([0-9]+)/", $link, $matches)) { return 'public'; } if (preg_match("/photo-?([0-9_]+)/", $link, $matches)) { return 'photo'; } if (!empty($item)) { return "post"; } $item = $doc['#group']; if (!empty($item)) { return "group"; } $item = $doc['#public']; if (!empty($item)) { return 'public'; } }
public function __construct($content, $params = []) { $this->dom = \phpQuery::newDocumentHTML($content); foreach ($params as $attribute => $value) { $this->{$attribute} = $value; } }
function getBody() { if ($this->parts && $this->body === null) { foreach ($this->parts as $part) { $partNo = $part['partNo']; $encoding = $part['encoding']; $charset = $part['charset']; $body = imap_fetchbody($this->message->getMailbox(), $this->message->getUID(), $partNo, FT_UID); $body = BrIMAP::decode($body, $encoding); if ($charset) { $body = @iconv($charset, 'UTF-8', $body); } $body = trim($body); $body = preg_replace('~<head[^>]*?>.*?</head>~ism', '', $body); $body = preg_replace('~<meta[^>]*?>~ism', '', $body); $body = preg_replace('~<base[^>]*?>~ism', '', $body); $body = preg_replace('~<style[^>]*?>.*?</style>~ism', '', $body); if ($this->isHTML && $body) { try { $doc = phpQuery::newDocument($body); $bodyTag = $doc->find('body'); if ($bodyTag->length() > 0) { $body = trim(pq($bodyTag)->html()); } else { $body = trim($doc->html()); } phpQuery::unloadDocuments(); } catch (Exception $e) { } } $this->body .= $body; } } return $this->body; }
public function getAllData() { $url = $this->getWebsiteUrl(); $parser = new Parser(); $html = $parser->getHtml($url); phpQuery::newDocumentHTML($html); $data = array(); $data['logo'] = $this->getLogo(); $data['sitename'] = "Sulekha.com"; foreach (pq(".box") as $item) { $class_Discount_bg = pq($item)->find(".dealimgst"); $href = pq($class_Discount_bg)->find("a")->attr("href"); $href = 'http://deals.sulekha.com' . $href; $actual_price = trim(pq($item)->find(".dlpristrk")->text()); $actual_price = (int) preg_replace('~\\D~', '', $actual_price); $img_src = pq($class_Discount_bg)->find("img")->attr("src"); $price = trim(pq($item)->find(".hgtlgtorg")->text()); $price = (int) preg_replace('~\\D~', '', $price); $off_percent = $actual_price - $price; $off_percent = number_format($off_percent) . "/-"; $price = number_format($price) . "/-"; $name = trim(pq($item)->find(".deallstit>a")->text()); //$time_left = pq($item)->find(".countdown_row")->text(); $data[] = array('name' => $name, 'href' => $href, 'price' => 'Rs.' . $price, 'image' => $img_src, 'off' => 'Rs.' . $off_percent); } return $data; }
public function run() { $content = ob_get_clean(); $formatted = phpQuery::newDocument($content); $imageNodes = pq('img'); foreach ($imageNodes as $imNode) { $imNode = pq($imNode); $imPath = $imNode->attr('src'); $thumbPath = $this->thumbsDir . '/' . basename($imPath); //$thumbPath = dirname($imPath).'/thumbs/'.basename($imPath); // Create thumbnail if not exists if (!file_exists($thumbPath)) { $imgObj = Yii::app()->simpleImage->load($imPath); if (!isset($this->thumbHeight)) { $imgObj->resizeToWidth($this->thumbWidth); } else { $imgObj->resize($this->thumbWidth, $this->thumbHeight); } $imgObj->save($thumbPath); } $imNode->wrap('<a href="' . $imPath . '" rel="gallery"></a>'); $imNode->attr('src', Yii::app()->request->baseUrl . DIRECTORY_SEPARATOR . $thumbPath); } echo $formatted; }