Пример #1
0
 /**
  * @param string $name
  * @return string
  */
 public function extractValue($name)
 {
     if (isset($this->extractedValues[$name])) {
         return $this->extractedValues[$name];
     }
     $mapping = isset($this->itemMapping[$name]) ? $this->itemMapping[$name] : $name;
     if (is_string($mapping)) {
         $mapping = array('selector' => $mapping);
     }
     $value = !empty($mapping['defaultValue']) ? $mapping['defaultValue'] : '';
     if (empty($mapping['selector']) && empty($mapping['defaultValue'])) {
         throw new \RuntimeException('Missing \'selector\' or \'defaultValue\' for ' . htmlentities($name) . ' mapping');
     }
     if (!empty($mapping['selector'])) {
         if (!empty($mapping['source'])) {
             $source = $this->extractorService->extractValue($this->item, $mapping['source']);
             $source = $this->extractorService->fetchRawContent($source);
             try {
                 $item = qp($source);
             } catch (\QueryPath\Exception $e) {
                 $item = htmlqp($source);
             }
         } else {
             $item = $this->item;
         }
         $value = $this->extractorService->extractValue($item, $mapping, $value);
     }
     $this->extractedValues[$name] = $value;
     return $this->extractedValues[$name];
 }
Пример #2
0
 public function tplArrayR($qp, $array, $options = NULL)
 {
     if (!is_array($array) && !$array instanceof Traversable) {
         $qp->append($array);
     } elseif ($this->isAssoc($array)) {
         foreach ($array as $k => $v) {
             $first = substr($k, 0, 1);
             if ($first != '.' && $first != '#') {
                 $k = '.' . $k;
             }
             if (is_array($v)) {
                 $this->tplArrayR($qp->top($k), $v, $options);
             } else {
                 $qp->branch()->children($k)->append($v);
             }
         }
     } else {
         foreach ($array as $entry) {
             $eles = $qp->get();
             $template = array();
             foreach ($eles as $ele) {
                 $template = $ele->cloneNode(TRUE);
             }
             $tpl = qp($template);
             $tpl = $this->tplArrayR($tpl, $entry, $options);
             $qp->before($tpl);
         }
         $dead = $qp->branch();
         $qp->parent();
         $dead->remove();
         unset($dead);
     }
     return $qp;
 }
 public function testXSLT()
 {
     // XML and XSLT taken from http://us.php.net/manual/en/xsl.examples-collection.php
     // and then modified to be *actually welformed* XML.
     $orig = '<?xml version="1.0"?><collection>
  <cd>
   <title>Fight for your mind</title>
   <artist>Ben Harper</artist>
   <year>1995</year>
  </cd>
  <cd>
   <title>Electric Ladyland</title>
   <artist>Jimi Hendrix</artist>
   <year>1997</year>
  </cd>
 </collection>';
     $template = '<?xml version="1.0"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:param name="owner" select="\'Nicolas Eliaszewicz\'"/>
  <xsl:output method="html" encoding="iso-8859-1" indent="no"/>
  <xsl:template match="collection">
   <div>
   Hey! Welcome to <xsl:value-of select="$owner"/>\'s sweet CD collection!
   <xsl:apply-templates/>
   </div>
  </xsl:template>
  <xsl:template match="cd">
   <h1><xsl:value-of select="title"/></h1>
   <h2>by <xsl:value-of select="artist"/> - <xsl:value-of select="year"/></h2>
   <hr />
  </xsl:template>
 </xsl:stylesheet>
 ';
     $qp = qp($orig)->xslt($template);
     $this->assertEquals(2, $qp->top('h1')->size(), 'Make sure that data was formatted');
 }
 public static function getThing($type_or_qp, $version = 0)
 {
     $thingNames = array_flip(HVRawConnector::$things);
     $typeId = '';
     if ($type_or_qp instanceof Query) {
         $typeId = $type_or_qp->top()->find('type-id')->text();
     } elseif (is_string($type_or_qp)) {
         $typeId = HealthRecordItemFactory::getTypeId($type_or_qp);
         $template = __DIR__ . '/HealthRecordItem/XmlTemplates/' . $typeId . '.xml';
         if (is_readable($template)) {
             $type_or_qp = qp(file_get_contents($template), NULL, array('use_parser' => 'xml'));
         }
     } else {
         throw new HVClientException('ThingFactory::getThing must be called with a valid thing name or type id or a QueryPath object representing a thing.');
     }
     if ($typeId) {
         if ($type_or_qp instanceof Query) {
             if ($className = HealthRecordItemFactory::convertThingNameToClassName($thingNames[$typeId])) {
                 return new $className($type_or_qp);
             } else {
                 throw new HVClientException('Things of that type id are not supported yet: ' . $typeId);
             }
         } else {
             throw new HVClientException('Creation of new empty things of that type id is not supported yet: ' . $typeId);
         }
     } else {
         throw new HVClientException('Unable to detect type id.');
     }
 }
Пример #5
0
 /**
  * Check IP address for present in public blacklists.
  *
  * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
  */
 public function index()
 {
     $ipAddress = Input::get('ipV4');
     $ipAddress = trim($ipAddress);
     if ($ipAddress == '') {
         $ipAddress = $_SERVER['REMOTE_ADDR'];
     }
     $checkPerformed = false;
     $inBlacklist = false;
     $blacklistInfoLinks = [];
     $checkerUrl = '';
     if (Input::get('check')) {
         $spamhausBaseUrl = 'http://www.spamhaus.org';
         $checkerUrl = $spamhausBaseUrl . '/query/ip/' . $ipAddress;
         // :TODO: Get with guzzle
         $data = file_get_contents($checkerUrl);
         foreach (qp($data, 'span.body') as $row) {
             $link = $row->find('ul li a')->attr('href');
             if ($link != '') {
                 $blacklistInfoLinks[] = $spamhausBaseUrl . $link;
             }
         }
         if (!empty($blacklistInfoLinks)) {
             $inBlacklist = true;
         }
         $checkPerformed = true;
     }
     return view('ip-blacklist.form', ['ipV4' => $ipAddress, 'inBlacklist' => $inBlacklist, 'blacklistInfoLinks' => $blacklistInfoLinks, 'checkerUrl' => $checkerUrl, 'checkPerformed' => $checkPerformed]);
 }
 public function test_header()
 {
     update_option('blogname', 'Unholy Site Title');
     update_option('blogdescription', 'Unholy Site Description');
     $dom = $this->get_permalink_as_dom('/');
     $this->assertEquals('Unholy Site Title', qp($dom, '#masthead .site-title')->text());
     $this->assertEquals('Unholy Site Description', qp($dom, '#masthead .site-description')->text());
 }
Пример #7
0
 public function test_rss_feed_loads_post()
 {
     $user_id = $this->factory->user->create(array('display_name' => 'Unholy Author'));
     $this->factory->post->create(array('post_title' => 'Unholy Post Title', 'post_author' => $user_id));
     $dom = $this->get_feed_as_dom(home_url('feed/'));
     $this->assertEquals('Unholy Post Title', qp($dom, 'channel item title')->eq(0)->text());
     $this->assertEquals('Unholy Author', qp($dom, 'channel item dc|creator')->eq(0)->text());
 }
 public function filterDate($date_start, $date_end)
 {
     $this->items = $this->items->filterCallback(function ($index, $item) use($date_start, $date_end) {
         $text = qp($item)->find('due_date')->text();
         $date = strtotime(implode('-', array_reverse(explode('/', $text))));
         return $date_start <= $date && $date <= $date_end;
     });
     return $this;
 }
Пример #9
0
function getHPFanficArchiveInfo($url)
{
    $urlParts = parse_url($url);
    parse_str($urlParts['query'], $query);
    if (isset($query['sid'])) {
        $storyId = $query['sid'];
        if (is_numeric($storyId)) {
            $url = "{$urlParts['scheme']}://{$urlParts['host']}/stories/viewstory.php?sid={$storyId}";
            $response = cURL($url);
            $html = new HTML5();
            $html = $html->loadHTML($response);
            $story = new Story();
            $story->id = $storyId;
            $story->url = $url;
            $title = qp($html, '#pagetitle')->find('a[href^="viewstory"]')->first()->text();
            if (empty($title)) {
                throw new FicSaveException("Could not retrieve title for story at {$url}.");
            } else {
                $story->title = $title;
            }
            $author = qp($html, '#pagetitle')->find('a[href^="viewuser"]')->first()->text();
            if (empty($author)) {
                throw new FicSaveException("Could not retrieve author for story at {$url}.");
            } else {
                $story->author = $author;
            }
            $description = qp($html, '#mainpage')->find('.block')->get(1);
            if ($description == NULL) {
                throw new FicSaveException("Could not retrieve description for story at {$url}.");
            } else {
                $story->description = stripAttributes(preg_replace('/<a(.*?)>(.*?)<\\/a>/', '\\2', trim(qp($description)->find('.content')->first()->innerHTML())));
            }
            $chaptersBlock = qp($html, '#mainpage')->find('.block')->get(3);
            if ($chaptersBlock == NULL) {
                throw new FicSaveException("Could not get number of chapters for story at {$url}.");
            } else {
                $chapterLinks = qp($chaptersBlock)->find('a[href^="viewstory"]');
                $numChapters = $chapterLinks->count();
                if ($numChapters > 0) {
                    $story->chapters = $numChapters;
                    $story->metadata = array();
                    foreach ($chapterLinks as $chapterLink) {
                        $story->metadata[] = $chapterLink->text();
                    }
                } else {
                    throw new FicSaveException("Could not get number of chapters for story at {$url}.");
                }
            }
            return $story;
        } else {
            throw new FicSaveException("URL has an invalid story ID: {$storyId}.");
        }
    } else {
        throw new FicSaveException("URL is missing story ID.");
    }
}
Пример #10
0
 private function eventPresenceDefault($room, $nick, $item, $stanza)
 {
     // away, dnd, xa, chat, [default].
     $show = \qp($stanza, 'show')->text() || 'default';
     $status = \qp($stanza, 'status')->text() || '';
     // Create the user object.
     $user = array('nick' => $nick, 'jid' => $item->attr('jid'), 'role' => $item->attr('role'), 'affiliation' => $item->attr('affiliation'), 'show' => $show, 'status' => $status);
     $this->roster[$room][$nick] = $user;
     l("[" . $room . "] " . $user['nick'] . " joined room");
 }
Пример #11
0
 public function xslt($style)
 {
     if (!$style instanceof QueryPath) {
         $style = qp($style);
     }
     $sourceDoc = $this->src->top()->get(0)->ownerDocument;
     $styleDoc = $style->get(0)->ownerDocument;
     $processor = new XSLTProcessor();
     $processor->importStylesheet($styleDoc);
     return qp($processor->transformToDoc($sourceDoc));
 }
 public function testQPOverrideOrder()
 {
     $expect = array('test1' => 'val3', 'test2' => 'val2');
     $options = array('test1' => 'val1', 'test2' => 'val2');
     Options::set($options);
     $qpOpts = qp(NULL, NULL, array('test1' => 'val3', 'replace_entities' => TRUE))->getOptions();
     $this->assertEquals($expect['test1'], $qpOpts['test1']);
     $this->assertEquals(TRUE, $qpOpts['replace_entities']);
     $this->assertNull($qpOpts['parser_flags']);
     $this->assertEquals($expect['test2'], $qpOpts['test2']);
 }
    public function testQPEntityReplacement()
    {
        $test = '<?xml version="1.0"?><root>&amp;&copy;&#38;& nothing.</root>';
        /*$expect = '<?xml version="1.0"?><root>&#38;&#169;&#38;&#38; nothing.</root>';*/
        // We get this because the DOM serializer re-converts entities.
        $expect = '<?xml version="1.0"?>
<root>&amp;&#xA9;&amp;&amp; nothing.</root>';
        $qp = qp($test, NULL, array('replace_entities' => TRUE));
        // Interestingly, the XML serializer converts decimal to hex and ampersands
        // to &amp;.
        $this->assertEquals($expect, trim($qp->xml()));
    }
Пример #14
0
function getFanfictionNetInfo($url)
{
    $urlParts = parse_url($url);
    $pathParts = explode('/', $urlParts['path']);
    if (isset($pathParts[2])) {
        $storyId = $pathParts[2];
        if (is_numeric($storyId)) {
            $response = cURL($url);
            $html = new HTML5();
            $html = $html->loadHTML($response);
            $story = new Story();
            $story->id = $storyId;
            $urlParts = parse_url($url);
            $story->url = "{$urlParts['scheme']}://{$urlParts['host']}/s/{$storyId}";
            $title = qp($html, '#profile_top')->find('b')->first()->text();
            if (empty($title)) {
                throw new FicSaveException("Could not retrieve title for story at {$url}.");
            } else {
                $story->title = $title;
            }
            $author = qp($html, '#profile_top')->find('a')->first()->text();
            if (empty($author)) {
                throw new FicSaveException("Could not retrieve author for story at {$url}.");
            } else {
                $story->author = $author;
            }
            $description = qp($html, '#profile_top')->find('div')->get(2);
            if ($description == NULL) {
                throw new FicSaveException("Could not retrieve description for story at {$url}.");
            } else {
                $story->description = stripAttributes(preg_replace('/<a(.*?)>(.*?)<\\/a>/', '\\2', trim(qp($description)->html() . qp($description)->next()->html())));
            }
            $numChapters = qp($html, '#chap_select')->find('option')->count() / 2;
            // value is always doubled for some reason
            $story->chapters = $numChapters == 0 ? 1 : $numChapters;
            $coverImageUrl = qp($html, '#profile_top')->find('img')->first()->attr('src');
            if ($coverImageUrl != NULL) {
                $coverImageUrlParts = parse_url($coverImageUrl);
                if (!isset($coverImageUrlParts['scheme']) && substr($coverImageUrl, 0, 2) == '//') {
                    $coverImageUrl = $urlParts['scheme'] . ":" . $coverImageUrl;
                }
                $coverImageUrl = str_replace('/75/', '/180/', $coverImageUrl);
                $story->coverImageUrl = $coverImageUrl;
            }
            return $story;
        } else {
            throw new FicSaveException("URL has an invalid story ID: {$storyId}.");
        }
    } else {
        throw new FicSaveException("URL is missing story ID.");
    }
}
Пример #15
0
 public function parents($selector = null)
 {
     $parents = $this->wrappedQuery->parents();
     if ($selector === null) {
         return $this->createQuery($parents);
     }
     $matchingParents = array();
     foreach ($parents as $parent) {
         if ($this->matcher->matches($parent->get(0), $selector)) {
             $matchingParents[] = $parent->get(0);
         }
     }
     return $this->createQuery(qp($matchingParents));
 }
Пример #16
0
 public function testQueryChains()
 {
     $sql = 'SELECT * FROM qpdb_test';
     $args = array();
     $qp = qp(QueryPath::HTML_STUB, 'body')->append('<h1></h1>')->children()->query($sql, $args)->nextRow()->appendColumn('colOne')->parent()->append('<p/>')->find('p')->nextRow()->prependColumn('colTwo')->columnAfter('colThree')->doneWithQuery();
     //->writeHTML(); // Write the output as HTML.
     $this->assertEquals('Title 0', $qp->top()->find('h1')->text());
     $this->assertEquals('Body 1', $qp->top()->find('p')->text());
     $qp = qp(QueryPath::HTML_STUB, 'body')->append('<table><tbody/></table>')->find('tbody')->query('SELECT * FROM qpdb_test LIMIT 2')->withEachRow()->appendColumn('colOne')->doneWithQuery();
     $this->assertEquals('Title 0Title 1', $qp->top()->find('tbody')->text());
     $wrap = '<tr><td/></tr>';
     $qp = qp(QueryPath::HTML_STUB, 'body')->append('<table><tbody/></table>')->find('tbody')->query('SELECT * FROM qpdb_test LIMIT 2')->withEachRow()->appendColumn('colOne', $wrap)->doneWithQuery();
     //->writeHTML();
     $this->assertEquals('Title 0', $qp->top()->find('td:first')->text());
 }
Пример #17
0
 public function testAppendTable()
 {
     $data = array('headers' => array('One', 'Two', 'Three'), 'rows' => array(array(1, 2, 3), array('Ein', 'Zwei', 'Drei'), array('uno', 'dos', 'tres'), array('uno', 'du')));
     $qp = qp(\QueryPath::HTML_STUB, 'body')->appendTable($data);
     $this->assertEquals(3, $qp->top()->find('th')->size());
     $this->assertEquals(11, $qp->top()->find('td')->size());
     $this->assertEquals('Zwei', $qp->eq(4)->text());
     // Test with an object instead...
     $o = new \QueryPath\Extension\QPTableData();
     $o->setHeaders($data['headers']);
     $o->setRows($data['rows']);
     $qp = qp(\QueryPath::HTML_STUB, 'body')->appendTable($o);
     $this->assertEquals(3, $qp->top()->find('th')->size());
     $this->assertEquals(11, $qp->top()->find('td')->size());
     $this->assertEquals('Zwei', $qp->eq(4)->text());
 }
Пример #18
0
 protected function listImpl($items, $type, $opts, $q = NULL)
 {
     $ele = '<' . $type . '/>';
     if (!isset($q)) {
         $q = qp()->append($ele)->addClass($opts['list class']);
     }
     foreach ($items as $li) {
         if ($li instanceof QueryPath) {
             $q = $this->listImpl($li->get(), $type, $opts, $q);
         } elseif (is_array($li) || $li instanceof Traversable) {
             $q->append('<li><ul/></li>')->find('li:last > ul');
             $q = $this->listImpl($li, $type, $opts, $q);
             $q->parent();
         } else {
             $q->append('<li>' . $li . '</li>');
         }
     }
     return $q;
 }
Пример #19
0
function getAsianFanficsInfo($url)
{
    $urlParts = parse_url($url);
    $pathParts = explode('/', $urlParts['path']);
    if (isset($pathParts[3])) {
        $storyId = $pathParts[3];
        if (is_numeric($storyId)) {
            $url = "{$urlParts['scheme']}://{$urlParts['host']}/story/view/{$storyId}";
            $response = cURL($url);
            $html = new HTML5();
            $html = $html->loadHTML($response);
            $story = new Story();
            $story->id = $storyId;
            $story->url = $url;
            $title = trim(qp($html, 'h1.title')->first()->text());
            if (empty($title)) {
                throw new FicSaveException("Could not retrieve title for story at {$url}.");
            } else {
                $story->title = $title;
            }
            $author = qp(qp($html, 'span.text--info')->get(0))->next()->text();
            if (empty($author)) {
                throw new FicSaveException("Could not retrieve author for story at {$url}.");
            } else {
                $story->author = $author;
            }
            $description = qp($html, '#bodyText')->find('h2')->first()->next();
            if ($description == NULL) {
                throw new FicSaveException("Could not retrieve description for story at {$url}.");
            } else {
                $story->description = stripAttributes(trim($description->innerHTML()));
            }
            $story->chapters = qp($html, 'select[name="chapterNav"]')->find('option')->count() - 1;
            return $story;
        } else {
            throw new FicSaveException("URL has an invalid story ID: {$storyId}.");
        }
    } else {
        throw new FicSaveException("URL is missing story ID.");
    }
}
Пример #20
0
function getAdultFanfictionOrgInfo($url)
{
    $urlParts = parse_url($url);
    parse_str($urlParts['query'], $query);
    if (isset($query['no'])) {
        $storyId = $query['no'];
        if (is_numeric($storyId)) {
            $response = cURL($url);
            $html = new HTML5();
            $html = $html->loadHTML($response);
            $story = new Story();
            $story->id = $storyId;
            $urlParts = parse_url($url);
            $story->url = "{$urlParts['scheme']}://{$urlParts['host']}/story.php?no={$storyId}";
            $title = trim(str_replace('Story:', '', qp($html, 'title')->text()));
            if (empty($title)) {
                throw new FicSaveException("Could not retrieve title for story at {$url}.");
            } else {
                $story->title = $title;
            }
            $author = trim(qp(qp($html, 'tr.catdis')->find('td')->get(1))->find('a')->text());
            if (empty($author)) {
                throw new FicSaveException("Could not retrieve author for story at {$url}.");
            } else {
                $story->author = $author;
            }
            $numChapters = qp($html, 'select[name=chapnav]')->find('option')->count();
            if ($numChapters > 0) {
                $story->chapters = $numChapters;
            } else {
                throw new FicSaveException("Could not get number of chapters for story at {$url}.");
            }
            return $story;
        } else {
            throw new FicSaveException("URL has an invalid story ID: {$storyId}.");
        }
    } else {
        throw new FicSaveException("URL is missing story ID.");
    }
}
Пример #21
0
 public function testPseudoClassLink()
 {
     $xml = '<?xml version="1.0"?><a><b href="foo"/><c href="foo"/></a>';
     $qp = qp($xml, ':link');
     $this->assertEquals(2, $qp->size());
 }
<article>
  <title>Use QueryPath for Fun and Profit</title>
  <author>
    <first>Matt</first>
    <last>Butcher</last>
  </author>
  <body>
  <![CDATA[
  <p>QueryPath is a great tool.</p>
  <p>Use it in many ways.</p>
  ]]>
  </body>
</article>';
// Now let's take this article and insert it into the database:
$qp = qp($article);
// We are going to store our insert params in here.
$params = array();
// First, let's get the title
$params[':title'] = $qp->find('title')->text();
// Next, let's get the name:
$params[':name'] = $qp->top()->find('author>last')->text() . ', ' . $qp->prev('first')->text();
// Finally, let's get the article content:
$params[':body'] = $qp->top()->find('body')->text();
// Here's the query we are going to run:
$sql = 'INSERT INTO qpdb_article (title, author, body) VALUES (:title, :name, :body)';
// Now we can insert this:
$qp->query($sql, $params);
// Finally, we can now read this information back out into an HTML document
qp(QueryPath::HTML_STUB, 'body')->queryInto('SELECT * FROM qpdb_article')->writeHTML();
// Finally, we clean up:
$qp->exec('DROP TABLE qpdb_article');
Пример #23
0
<?php

require_once APPPATH . "/third_party/querypath-2.1.2/QueryPath/QueryPath.php";
qp('http://jmnote.com/html5/sample.php')->find('title')->text('Hello World')->writeHTML();
Пример #24
0
 /**
  * @param string $serverName
  * @param string $action
  * @param string $proxyName
  *
  * @return bool
  */
 public function setServerStatus($serverName, $action = 'enable', $proxyName = 'all')
 {
     // perform action on all proxies where server exists
     if ($proxyName == 'all') {
         $proxyNames = array();
         $stats = $this->getStatsByProxy();
         foreach ($stats as $proxyName => $serviceNames) {
             if (array_key_exists($serverName, $serviceNames)) {
                 $proxyNames[] = $proxyName;
             }
         }
     } else {
         $proxyNames = array($proxyName);
     }
     foreach ($proxyNames as $proxyName) {
         try {
             $this->_client->setMethod(Request::METHOD_POST);
             $this->_client->setParameterPost(array('s' => $serverName, 'b' => $proxyName, 'action' => $action));
             $this->_client->send();
         } catch (\Exception $e) {
             $this->_log('crit', "Exception: " . $e->getCode() . '-' . $e->getMessage());
             $this->_log('debug', "Exception Trace: " . $e->getTraceAsString());
         }
         $response = $this->_client->getResponse();
         if ($response->isSuccess()) {
             $this->_log('info', ucwords($action) . "d '{$serverName}' in proxy '{$proxyName}' on {$this->_serverFqdn}");
             // get the status notice displayed on the page
             /** @noinspection PhpUndefinedMethodInspection */
             $notice = str_replace(array('[X]', '.'), '', qp($response->getBody(), 'div')->text());
             $this->_log('debug', "HAProxy response on {$this->_serverFqdn}: {$notice}");
         } else {
             $this->_log('err', "Failed to {$action} '{$serverName}' in proxy '{$proxyName}' on {$this->_serverFqdn}");
             $this->_log('debug', "Response: " . $response->getStatusCode() . ' - ' . $response->getReasonPhrase());
         }
     }
 }
<?php

/** @file
 * Using QueryPath.
 *
 * This file contains an example of how QueryPath can be used
 * to generate web pages. Part of the design of this example is to exhibit many
 * different QueryPath functions in one long chain. All of the methods shown 
 * here are fully documented in {@link QueryPath}.
 *
 * The method used in this example is a typical example of how QueryPath can 
 * gradually build up content. Other methods include using {@link QPTPL} for 
 * templates, injecting database information with {@link QPDB}, and merging
 * data from one QueryPath to another.
 *
 * @author M Butcher <*****@*****.**>
 * @license LGPL The GNU Lesser GPL (LGPL) or an MIT-like license.
 */
require_once '../src/qp.php';
// Begin with an HTML stub document (XHTML, actually), and navigate to the title.
qp(QueryPath::HTML_STUB, 'title')->text('Example of QueryPath.')->top('body')->append('<h1>This is a test page</h1><p>Test text</p>')->children('p')->attr('class', 'some-class')->css('background-color', '#eee')->parent()->prepend('<table id="my-table"></table>')->top('#my-table')->append('<tr></tr><tr></tr>')->children()->addClass('table-row')->eq(0)->append('<th>This is the header</th>')->next()->append('<td>This is the data</td>')->writeHTML();
<?php

/**
 * Basic example of QueryPath usage.
 *
 * This two-line example exhibits basic use of QueryPath. It creates a new 
 * HTML document and adds the typical 'Hello World' text to the body. It then writes
 * that information to standard out (which is flushed to a web browser in most cases.)
 *
 * The important methods covered here are {@link qp()}, which is the {@link QueryPath}
 * factory function, {@link QueryPath::find()}, which is the primary searching 
 * function, and {@link QueryPath::writeHTML()}, which is a utility function.
 *
 * This file is fully explained in the official QueryPath tutorial, located 
 * at {@link https://fedorahosted.org/querypath/wiki/QueryPathTutorial}
 *
 * 
 * @author M Butcher <*****@*****.**>
 * @license LGPL The GNU Lesser GPL (LGPL) or an MIT-like license.
 * @see qp()
 * @see QueryPath::find()
 * @see QueryPath::writeHTML()
 * @see html.php
 * @see https://fedorahosted.org/querypath/wiki/QueryPathTutorial The Official Tutorial
 */
require_once '../src/QueryPath/QueryPath.php';
qp(QueryPath::HTML_STUB)->find('body')->text('Hello World')->writeHTML();
$qp = htmlqp(QueryPath::HTML_STUB, 'body');
$qp->append('<div></div><p id="cool">Hello</p><p id="notcool">Goodbye</p>')->children('p')->after('<p id="new">new paragraph</p>');
echo $qp->find('p')->children('p')->html() ? 'print' : 'dont print';
//         ->writeHTML();
Пример #27
0
 public function current()
 {
     return qp(parent::current(), NULL, $this->options);
 }
Пример #28
0
 public function testProcessingInstruction()
 {
     $this->assertEquals('This is a processing instruction.', trim(qp($this->file, 'third')->pi()));
     $msg = "Message";
     $this->assertEquals($msg, qp($this->file, 'second')->pi('qp', $msg)->top()->find('second')->pi());
 }
Пример #29
0
 */
require_once '../querypath-2.0-alpha2/src/QueryPath/QueryPath.php';
// The URL to look up
$url = "";
$url = 'http://dbpedia.org/data/Denmark.rdf';
// HTTP headers:
$headers = array('Accept: application/rdf,application/rdf+xml;q=0.9,*/*;q=0.8', 'Accept-Language: en-us,en', 'Accept-Charset: ISO-8859-1,utf-8', 'User-Agent: QueryPath/1.2');
// The context options:
$options = array('http' => array('method' => 'GET', 'protocol_version' => 1.1, 'header' => implode("\r\n", $headers)));
// Create a stream context that will tell QueryPath how to
// load the file.
$cxt = stream_context_create($options);
// Fetch the URL and select all rdf:Description elements.
// (Note that | is the CSS 3 equiv of colons for namespacing.)
// To add the context, we pass it in as an option to QueryPath.
$qp = qp($url, 'rdf|Description', array('context' => $cxt));
//$qp = qp('The_Beatles.rdf');
printf("<p>There are %d descriptions in this record.\n", $qp->size());
// Here, we use rdf|* to select all elements in the RDF namespace.
$qp->top()->find('rdf|about');
printf("<p>There are %d RDF items in this record.\n", $qp->size());
// Standard pseudo-classes that are not HTML specific can be used on
// namespaced elements, too.
// print "About: " . $qp->top()->find('rdfs|label:first')->text() . PHP_EOL;
// print "About (FOAF): " . $qp->top()->find('foaf|name:first')->text() . PHP_EOL;
// Namespaced attributes can be retrieved using the same sort of delimiting.
// print "\nComment:\n";
// print $qp->top()->find('rdfs|comment[xml|lang="en"]')->text();
// print PHP_EOL;
// $qp->top();
// print "\nImages:\n";
 * @see QueryPath
 * 
 * @author M Butcher <*****@*****.**>
 * @license LGPL (The GNU Lesser GPL) or an MIT-like license.
 */
require '../src/QueryPath/QueryPath.php';
$demo = '<?xml version="1.0" ?>
<data>
<li>Foo</li>
<li>Foo</li>
<li>Foo</li>
<li>Foo</li>
<li>Foo</li>
</data>
';
$qp = qp($demo, 'data');
// Iterate over elements as DOMNodes:
foreach ($qp->get() as $li_ele) {
    print $li_ele->tagName . PHP_EOL;
    // Prints 'li' five times.
}
// Iterate over elements as QueryPath objects
foreach ($qp as $li_qp) {
    print $li_qp->tag() . PHP_EOL;
    // Prints 'li' five times
}
function callbackFunction($index, $element)
{
    print $element->tagName . PHP_EOL;
}
// Iterate using a callback function