Beispiel #1
0
 /**
  * Method to load a URI into the feed reader for parsing.
  *
  * @param   string  $uri  The URI of the feed to load. Idn uris must be passed already converted to punycode.
  *
  * @return  JFeedReader
  *
  * @since   12.3
  * @throws  InvalidArgumentException
  * @throws  RuntimeException
  */
 public function getFeed($uri)
 {
     // Create the XMLReader object.
     $reader = new XMLReader();
     // Open the URI within the stream reader.
     if (!@$reader->open($uri, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
         // If allow_url_fopen is enabled
         if (ini_get('allow_url_fopen')) {
             // This is an error
             throw new RuntimeException('Unable to open the feed.');
         } else {
             // Retry with JHttpFactory that allow using CURL and Sockets as alternative method when available
             $connector = JHttpFactory::getHttp();
             $feed = $connector->get($uri);
             // Set the value to the XMLReader parser
             if (!$reader->xml($feed->body, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
                 throw new RuntimeException('Unable to parse the feed.');
             }
         }
     }
     try {
         // Skip ahead to the root node.
         while ($reader->read()) {
             if ($reader->nodeType == XMLReader::ELEMENT) {
                 break;
             }
         }
     } catch (Exception $e) {
         throw new RuntimeException('Error reading feed.');
     }
     // Setup the appopriate feed parser for the feed.
     $parser = $this->_fetchFeedParser($reader->name, $reader);
     return $parser->parse();
 }
Beispiel #2
0
 /**
  * Method to load a URI into the feed reader for parsing.
  *
  * @param   string  $uri  The URI of the feed to load. Idn uris must be passed already converted to punycode.
  *
  * @return  JFeedReader
  *
  * @since   12.3
  * @throws  InvalidArgumentException
  * @throws  RuntimeException
  */
 public function getFeed($uri)
 {
     // Create the XMLReader object.
     $reader = new XMLReader();
     // Open the URI within the stream reader.
     if (!@$reader->open($uri, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
         // Retry with JHttpFactory that allow using CURL and Sockets as alternative method when available
         // Adding a valid user agent string, otherwise some feed-servers returning an error
         $options = new \joomla\Registry\Registry();
         $options->set('userAgent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0');
         $connector = JHttpFactory::getHttp($options);
         $feed = $connector->get($uri);
         if ($feed->code != 200) {
             throw new RuntimeException('Unable to open the feed.');
         }
         // Set the value to the XMLReader parser
         if (!$reader->xml($feed->body, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
             throw new RuntimeException('Unable to parse the feed.');
         }
     }
     try {
         // Skip ahead to the root node.
         while ($reader->read()) {
             if ($reader->nodeType == XMLReader::ELEMENT) {
                 break;
             }
         }
     } catch (Exception $e) {
         throw new RuntimeException('Error reading feed.', $e->getCode(), $e);
     }
     // Setup the appopriate feed parser for the feed.
     $parser = $this->_fetchFeedParser($reader->name, $reader);
     return $parser->parse();
 }
 /**
  * Parse the passed in Sparql XML string into a more easily usable format.
  *
  * @param string $sparql
  *   A string containing Sparql result XML.
  *
  * @return array
  *   Indexed (numerical) array, containing a number of associative arrays,
  *   with keys being the same as the variable names in the query.
  *   URIs beginning with 'info:fedora/' will have this beginning stripped
  *   off, to facilitate their use as PIDs.
  */
 public static function parseSparqlResults($sparql)
 {
     // Load the results into a XMLReader Object.
     $xmlReader = new XMLReader();
     $xmlReader->xml($sparql);
     // Storage.
     $results = array();
     // Build the results.
     while ($xmlReader->read()) {
         if ($xmlReader->localName === 'result') {
             if ($xmlReader->nodeType == XMLReader::ELEMENT) {
                 // Initialize a single result.
                 $r = array();
             } elseif ($xmlReader->nodeType == XMLReader::END_ELEMENT) {
                 // Add result to results
                 $results[] = $r;
             }
         } elseif ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->depth == 3) {
             $val = array();
             $uri = $xmlReader->getAttribute('uri');
             if ($uri !== NULL) {
                 $val['value'] = self::pidUriToBarePid($uri);
                 $val['uri'] = (string) $uri;
                 $val['type'] = 'pid';
             } else {
                 //deal with any other types
                 $val['type'] = 'literal';
                 $val['value'] = (string) $xmlReader->readInnerXML();
             }
             $r[$xmlReader->localName] = $val;
         }
     }
     $xmlReader->close();
     return $results;
 }
 /**
  * Execute parsing
  *
  * @param string $input
  * @return mixed
  */
 public function execute($input)
 {
     $reader = new BasicXmlReader();
     $reader->xml($input);
     $data = $this->xmlToArray($reader);
     return $this->arrayToResource($data);
 }
 /**
  * Convert string with xml data to php array.
  *
  * @throws Exception
  *
  * @param string $string
  *
  * @return array
  */
 public function read($string)
 {
     libxml_use_internal_errors(true);
     libxml_disable_entity_loader(true);
     $result = simplexml_load_string($string, null, LIBXML_IMPORT_FLAGS);
     if (!$result) {
         $errors = libxml_get_errors();
         libxml_clear_errors();
         foreach ($errors as $error) {
             $text = '';
             switch ($error->level) {
                 case LIBXML_ERR_WARNING:
                     $text .= _s('XML file contains warning %1$s:', $error->code);
                     break;
                 case LIBXML_ERR_ERROR:
                     $text .= _s('XML file contains error %1$s:', $error->code);
                     break;
                 case LIBXML_ERR_FATAL:
                     $text .= _s('XML file contains fatal error %1$s:', $error->code);
                     break;
             }
             $text .= trim($error->message) . ' [ Line: ' . $error->line . ' | Column: ' . $error->column . ' ]';
             throw new Exception($text);
         }
     }
     $xml = new XMLReader();
     $xml->xml($string);
     $array = $this->xmlToArray($xml);
     $xml->close();
     return $array;
 }
Beispiel #6
0
 public function readString($string, $class)
 {
     $reader = new \XMLReader();
     //        $reader->setParserProperty(\XMLReader::VALIDATE, true);
     $reader->xml($string);
     $ret = $this->readXml($reader, $class);
     $reader->close();
     return $ret;
 }
Beispiel #7
0
function foo()
{
    for ($i = 0; $i < 100; $i++) {
        $reader = new XMLReader();
        $reader->xml('<?xml version="1.0" encoding="utf-8"?><id>1234567890</id>');
        while ($reader->read()) {
            $reader->expand();
        }
    }
}
Beispiel #8
0
 /**
  * Parses given xml by xmlPathConfig of this class.
  *
  * @param string $xml The XML as string.
  *
  * @return array The processed xml as array.
  * @throws VersionControl_SVN_Parser_Exception If XML isn't parseable.
  */
 public function getParsed($xml)
 {
     $reader = new XMLReader();
     $reader->xml($xml);
     if (false === $reader) {
         throw new VersionControl_SVN_Parser_Exception('Cannot instantiate XMLReader');
     }
     $data = self::getParsedBody($reader, $this->xmlPathConfig);
     $reader->close();
     return $data;
 }
Beispiel #9
0
 /**
  * Should convert php arrays to valid xml.
  */
 public function testEncode()
 {
     $ops = new Ops();
     $data = array('protocol' => '', 'action' => '', 'object' => '');
     $result = $ops->encode($data);
     $xml = XMLReader::xml($result);
     // The validate parser option must be enabled for
     // this method to work properly
     $xml->setParserProperty(XMLReader::VALIDATE, true);
     // make sure this is xml
     $this->assertTrue($xml->isValid());
 }
 /**
  * Return a JS file in the container in links.
  *
  * @param string $xml
  * 
  * @return string
  * @access public
  * @author Etienne de Longeaux <*****@*****.**>
  */
 public function map($xml)
 {
     $reader = new \XMLReader();
     $reading = $reader->xml($xml);
     $reader->read();
     foreach ($this->mappers as $mapper) {
         if ($mapper->supports($reader->name)) {
             return $mapper->map($xml, $this);
         }
     }
     throw new \Exception('No registered mapper for ' . $reader->name);
 }
 /**
  * Deserialize the resource from the specified input stream.
  *
  * @param string $incoming The text to deserialize.
  *
  * @return mixed the resource.
  */
 public function deserialize($incoming)
 {
     $resources = null;
     $reader = new \XMLReader();
     $reader->xml($incoming);
     $reader->read();
     do {
         if ($reader->nodeType == \XMLReader::ELEMENT && XmlMapper::isKnownType($reader->name)) {
             $class = XmlMapper::getClassName($reader->name);
             $resources[] = new $class($reader);
         }
     } while ($reader->read());
     return $resources;
 }
 /**
  * testViewRss
  *
  */
 public function testViewRss()
 {
     // Disable debug mode to avoid DebugKit interruption
     $debug = Configure::read('debug');
     Configure::write('debug', 0);
     $this->testAction('/categories/view/1.rss', array('method' => 'GET', 'return' => 'contents'));
     // Restore debug setting
     Configure::write('debug', $debug);
     $expected_strings = array('Books', 'TestSlide1', 'TestSlide2');
     foreach ($expected_strings as $str) {
         $this->assertRegExp("/" . preg_quote($str) . "/", $this->contents);
     }
     $z = new XMLReader();
     $z->xml($this->contents, NULL, LIBXML_DTDVALID);
     $this->assertTrue($z->isValid());
 }
 /**
  * Read an RSS feed, and return its items.
  *
  * @param unknown $uri
  * @return array
  * */
 public function read($uri)
 {
     $xml = new XMLReader();
     $xml->xml(file_get_contents($uri));
     $items = array();
     $cur_item = null;
     $in_item = false;
     $cur_node = null;
     while ($xml->read()) {
         if ($xml->nodeType === XMLReader::ELEMENT && $xml->name === "item") {
             $cur_item = new stdClass();
             $cur_item->headline = null;
             $cur_item->body = null;
             $cur_item->uri = null;
             $cur_item->pub_date = null;
             $cur_item->category = null;
             $in_item = true;
         } elseif ($xml->nodeType === XMLReader::ELEMENT) {
             $cur_node = $xml->name;
         } elseif (($xml->nodeType === XMLReader::TEXT || $xml->nodeType === XMLReader::CDATA) && $in_item === true) {
             switch ($cur_node) {
                 case "title":
                     $cur_item->headline = $xml->value;
                     break;
                 case "description":
                     $cur_item->body = $xml->value;
                     break;
                 case "link":
                     $cur_item->uri = $xml->value;
                     break;
                 case "pubDate":
                     $cur_item->pub_date = $xml->value;
                     break;
                 case "category":
                     $cur_item->category = $xml->value;
                     break;
                 default:
                     break;
             }
         } elseif ($xml->nodeType === XMLReader::END_ELEMENT && $xml->name === "item") {
             $items[] = $cur_item;
             $in_item = false;
         }
     }
     return $items;
 }
Beispiel #14
0
 protected function _getReader($data, $request)
 {
     if (!is_bool($request)) {
     }
     /// @TODO
     $this->_currentNode = NULL;
     $reader = new XMLReader();
     $reader->xml($data, NULL, LIBXML_NONET | LIBXML_NOENT);
     if ($this->_validate) {
         if ('@data_dir@' != '@' . 'data_dir' . '@') {
             $schema = '@data_dir@' . DIRECTORY_SEPARATOR . 'pear.erebot.net' . DIRECTORY_SEPARATOR . 'XRL';
         } else {
             $schema = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'data';
         }
         $schema .= DIRECTORY_SEPARATOR;
         $schema .= $request ? 'request.rng' : 'response.rng';
         $reader->setRelaxNGSchema($schema);
     }
     return $reader;
 }
function parse_GetObs($output)
{
    $bookList = array();
    $i = 0;
    $xmlReader = new XMLReader();
    $xmlReader->xml($output);
    while ($xmlReader->read()) {
        // check to ensure nodeType is an Element not attribute or #Text
        if ($xmlReader->nodeType == XMLReader::ELEMENT) {
            if ($xmlReader->localName == 'values') {
                // move to its textnode / child
                $xmlReader->read();
                $bookList[$i]['values'] = $xmlReader->value;
                $i = $i + 1;
            }
        }
    }
    //print_r($bookList);
    return $bookList;
}
 /**
  * Convert string with xml data to php array.
  *
  * @throws Exception
  *
  * @param string $string
  *
  * @return array
  */
 public function read($string)
 {
     if ($string === '') {
         throw new Exception(_s('Cannot read XML: %1$s.', _('XML is empty')));
     }
     libxml_use_internal_errors(true);
     libxml_disable_entity_loader(true);
     $result = simplexml_load_string($string, null, LIBXML_IMPORT_FLAGS);
     if (!$result) {
         $errors = libxml_get_errors();
         libxml_clear_errors();
         foreach ($errors as $error) {
             throw new Exception(_s('Cannot read XML: %1$s.', _s('%1$s [Line: %2$s | Column: %3$s]', '(' . $error->code . ') ' . trim($error->message), $error->line, $error->column)));
         }
     }
     $xml = new XMLReader();
     $xml->xml($string);
     $data = $this->xml_to_array($xml);
     $xml->close();
     return $data;
 }
 /**
  * Scans conntent for cachedUntil and error
  *   
  * @param string $content
  * @param int $errorCode
  * @param string $errorText
  */
 protected function scanContent($content, &$errorCode, &$errorText)
 {
     $this->cachedUntil = null;
     $reader = new XMLReader();
     $reader->xml($content);
     while ($reader->read()) {
         if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == "error") {
             // got an error
             $errorText = $reader->readString();
             $errorCode = intval($reader->getAttribute('code'));
             if ($reader->next("cachedUntil")) {
                 $this->cachedUntil = $reader->readString();
             }
         } else {
             if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == "result") {
                 // no errors, we need to read the cache time though
                 if ($reader->next("cachedUntil")) {
                     $this->cachedUntil = $reader->readString();
                 }
             }
         }
     }
     $reader->close();
 }
Beispiel #18
0
 public function _get_conferences()
 {
     $bbconf = array();
     foreach (Doctrine_Query::create()->select("n.number,e.name,e.conference_id")->from("Number n,Conference e")->where("n.class_type='ConferenceNumber'")->andWhere("n.foreign_id=e.conference_id")->orderBy("e.name")->execute(array(), Doctrine::HYDRATE_SCALAR) as $conference) {
         $bbconf["conference_" . $conference["e_conference_id"]] = $conference;
     }
     $clid = array();
     foreach (Doctrine::getTable('Device')->findAll() as $ext) {
         if (array_key_exists('callerid', $ext['plugins']) && array_key_exists('internal_name', $ext['plugins']['callerid']) && array_key_exists('internal_number', $ext['plugins']['callerid'])) {
             if (array_key_exists('sip', $ext['plugins']) && array_key_exists('username', $ext['plugins']['sip'])) {
                 $clid[$ext['plugins']['sip']['username']] = array('name' => $ext['plugins']['callerid']['internal_name'], 'ext' => $ext['plugins']['callerid']['internal_number']);
             }
         }
     }
     $esl = new EslManager();
     $res = $esl->api("conference xml_list");
     $xml = new XMLReader();
     $xml->xml($esl->getResponse($res));
     $conferences = array();
     $path = array();
     while ($xml->read()) {
         if ($xml->nodeType == XMLReader::ELEMENT) {
             array_unshift($path, $xml->name);
             if ($xml->name == 'conference') {
                 $conferences[] = array();
                 end($conferences);
                 $conf =& $conferences[key($conferences)];
                 $current =& $conferences[key($conferences)];
                 $conf['members'] = array();
             } elseif ($xml->name == 'member') {
                 $key = count($conf['members']);
                 $conf['members'][$key] = array();
                 $member =& $conf['members'][$key];
                 $current =& $conf['members'][$key];
             }
             if ($xml->hasAttributes) {
                 while ($xml->moveToNextAttribute()) {
                     $current[$xml->name] = $xml->value;
                     if ($xml->name == 'name' && array_key_exists($xml->value, $bbconf)) {
                         $current['bluebox'] = $bbconf[$xml->value];
                     }
                 }
             }
         } elseif ($xml->nodeType == XMLReader::END_ELEMENT) {
             array_shift($path);
         } elseif ($xml->nodeType == XMLReader::TEXT) {
             $current[$path[0]] = $xml->value;
             if ($path[0] == "caller_id_number" && array_key_exists($xml->value, $clid)) {
                 $current['clid'] = $clid[$xml->value];
             }
         }
     }
     return $conferences;
 }
Beispiel #19
0
<?php

echo "Test\n";
$xmlreader = new XMLReader();
$xmlreader->xml("<a><b/></a>");
$xmlreader->next();
$xmlreader2 = clone $xmlreader;
$xmlreader2->next();
?>
Done
Beispiel #20
0
<?php

$data = '<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />
</Students>';
$xml = new XMLReader();
$xml->xml($data);
while ($xml->read()) {
    if (XMLREADER::ELEMENT == $xml->nodeType && $xml->localName == 'Student') {
        echo $xml->getAttribute('Name') . "\n";
    }
}
Beispiel #21
0
<?php

$reader = new XMLReader();
$reader->xml('<?xml version="1.0" encoding="UTF-8"?><ZohoAPIError><error code="API104" message="Invalid authorization header"/></ZohoAPIError>');
$reader->read();
var_dump($reader->attributes === null);
 /**
  * Not for use with big dataset
  */
 public static function xml2assoc($xmldata)
 {
     $xml = new XMLReader();
     $xml->xml($xmldata);
     $assoc = self::_xml2assoc($xml);
     $xml->close();
     return $assoc;
 }
Beispiel #23
0
 /**
  * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
  *
  * @param   string     $pFilename
  * @throws   PHPExcel_Reader_Exception
  */
 public function listWorksheetInfo($pFilename)
 {
     // Check if file exists
     if (!file_exists($pFilename)) {
         throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
     }
     $xml = new XMLReader();
     $xml->xml($this->securityScanFile('compress.zlib://' . realpath($pFilename)), null, PHPExcel_Settings::getLibXmlLoaderOptions());
     $xml->setParserProperty(2, true);
     $worksheetInfo = array();
     while ($xml->read()) {
         if ($xml->name == 'gnm:Sheet' && $xml->nodeType == XMLReader::ELEMENT) {
             $tmpInfo = array('worksheetName' => '', 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0);
             while ($xml->read()) {
                 if ($xml->name == 'gnm:Name' && $xml->nodeType == XMLReader::ELEMENT) {
                     $xml->read();
                     //    Move onto the value node
                     $tmpInfo['worksheetName'] = (string) $xml->value;
                 } elseif ($xml->name == 'gnm:MaxCol' && $xml->nodeType == XMLReader::ELEMENT) {
                     $xml->read();
                     //    Move onto the value node
                     $tmpInfo['lastColumnIndex'] = (int) $xml->value;
                     $tmpInfo['totalColumns'] = (int) $xml->value + 1;
                 } elseif ($xml->name == 'gnm:MaxRow' && $xml->nodeType == XMLReader::ELEMENT) {
                     $xml->read();
                     //    Move onto the value node
                     $tmpInfo['totalRows'] = (int) $xml->value + 1;
                     break;
                 }
             }
             $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']);
             $worksheetInfo[] = $tmpInfo;
         }
     }
     return $worksheetInfo;
 }
Beispiel #24
0
 public function parse(&$data, $encoding)
 {
     // Use UTF-8 if we get passed US-ASCII, as every US-ASCII character is a UTF-8 character
     if (strtoupper($encoding) === 'US-ASCII') {
         $this->encoding = 'UTF-8';
     } else {
         $this->encoding = $encoding;
     }
     // Strip BOM:
     // UTF-32 Big Endian BOM
     if (substr($data, 0, 4) === "��") {
         $data = substr($data, 4);
     } elseif (substr($data, 0, 4) === "��") {
         $data = substr($data, 4);
     } elseif (substr($data, 0, 2) === "��") {
         $data = substr($data, 2);
     } elseif (substr($data, 0, 2) === "��") {
         $data = substr($data, 2);
     } elseif (substr($data, 0, 3) === "") {
         $data = substr($data, 3);
     }
     if (substr($data, 0, 5) === '<?xml' && strspn(substr($data, 5, 1), "\t\n\r ") && ($pos = strpos($data, '?>')) !== false) {
         $declaration = $this->registry->create('XML_Declaration_Parser', array(substr($data, 5, $pos - 5)));
         if ($declaration->parse()) {
             $data = substr($data, $pos + 2);
             $data = '<?xml version="' . $declaration->version . '" encoding="' . $encoding . '" standalone="' . ($declaration->standalone ? 'yes' : 'no') . '"?>' . $data;
         } else {
             $this->error_string = 'SimplePie bug! Please report this!';
             return false;
         }
     }
     $return = true;
     static $xml_is_sane = null;
     if ($xml_is_sane === null) {
         $parser_check = xml_parser_create();
         xml_parse_into_struct($parser_check, '<foo>&amp;</foo>', $values);
         xml_parser_free($parser_check);
         $xml_is_sane = isset($values[0]['value']);
     }
     // Create the parser
     if ($xml_is_sane) {
         $xml = xml_parser_create_ns($this->encoding, $this->separator);
         xml_parser_set_option($xml, XML_OPTION_SKIP_WHITE, 1);
         xml_parser_set_option($xml, XML_OPTION_CASE_FOLDING, 0);
         xml_set_object($xml, $this);
         xml_set_character_data_handler($xml, 'cdata');
         xml_set_element_handler($xml, 'tag_open', 'tag_close');
         // Parse!
         if (!xml_parse($xml, $data, true)) {
             $this->error_code = xml_get_error_code($xml);
             $this->error_string = xml_error_string($this->error_code);
             $return = false;
         }
         $this->current_line = xml_get_current_line_number($xml);
         $this->current_column = xml_get_current_column_number($xml);
         $this->current_byte = xml_get_current_byte_index($xml);
         xml_parser_free($xml);
         return $return;
     } else {
         libxml_clear_errors();
         $xml = new XMLReader();
         $xml->xml($data);
         while (@$xml->read()) {
             switch ($xml->nodeType) {
                 case constant('XMLReader::END_ELEMENT'):
                     if ($xml->namespaceURI !== '') {
                         $tagName = $xml->namespaceURI . $this->separator . $xml->localName;
                     } else {
                         $tagName = $xml->localName;
                     }
                     $this->tag_close(null, $tagName);
                     break;
                 case constant('XMLReader::ELEMENT'):
                     $empty = $xml->isEmptyElement;
                     if ($xml->namespaceURI !== '') {
                         $tagName = $xml->namespaceURI . $this->separator . $xml->localName;
                     } else {
                         $tagName = $xml->localName;
                     }
                     $attributes = array();
                     while ($xml->moveToNextAttribute()) {
                         if ($xml->namespaceURI !== '') {
                             $attrName = $xml->namespaceURI . $this->separator . $xml->localName;
                         } else {
                             $attrName = $xml->localName;
                         }
                         $attributes[$attrName] = $xml->value;
                     }
                     $this->tag_open(null, $tagName, $attributes);
                     if ($empty) {
                         $this->tag_close(null, $tagName);
                     }
                     break;
                 case constant('XMLReader::TEXT'):
                 case constant('XMLReader::CDATA'):
                     $this->cdata(null, $xml->value);
                     break;
             }
         }
         if ($error = libxml_get_last_error()) {
             $this->error_code = $error->code;
             $this->error_string = $error->message;
             $this->current_line = $error->line;
             $this->current_column = $error->column;
             return false;
         } else {
             return true;
         }
     }
 }
Beispiel #25
0
 /**
  * Retrieves items from an OAI-enabled url.
  *
  * @param  JTable  $harvest  The harvesting details.
  */
 public function onJHarvestRetrieve($harvest)
 {
     $params = new \Joomla\Registry\Registry();
     $params->loadString($harvest->params);
     if ($params->get('discovery.type') != 'oai') {
         return;
     }
     $resumptionToken = null;
     $http = JHttpFactory::getHttp();
     $metadataPrefix = $params->get('discovery.plugin.metadata');
     do {
         $queries = array();
         if ($resumptionToken) {
             $queries['resumptionToken'] = $resumptionToken;
             // take a break to avoid any timeout issues.
             if (($sleep = $params->get('follow_on', self::FOLLOW_ON)) != 0) {
                 sleep($sleep);
             }
         } else {
             $queries['metadataPrefix'] = $metadataPrefix;
             if ($harvest->harvested != JFactory::getDbo()->getNullDate()) {
                 $queries['from'] = JFactory::getDate($harvest->harvested)->format('Y-m-d\\TH:i:s\\Z');
             }
             if ($set = $params->get('set')) {
                 $queries['set'] = $set;
             }
             $queries['until'] = $harvest->now->format('Y-m-d\\TH:i:s\\Z');
         }
         $url = new JUri($params->get('discovery.url'));
         $url->setQuery($queries);
         $url->setVar('verb', 'ListRecords');
         JHarvestHelper::log('Retrieving ' . (string) $url . ' for harvest...', JLog::DEBUG);
         $response = $http->get($url);
         $reader = new XMLReader();
         $reader->xml($response->body);
         $prefix = null;
         $identifier = null;
         $resumptionToken = null;
         // empty the resumptionToken to force a reload per page.
         while ($reader->read()) {
             if ($reader->nodeType == XMLReader::ELEMENT) {
                 $doc = new DOMDocument();
                 $doc->appendChild($doc->importNode($reader->expand(), true));
                 $node = simplexml_load_string($doc->saveXML());
                 $attributes = (array) $node->attributes();
                 if (isset($attributes['@attributes'])) {
                     $attributes = $attributes['@attributes'];
                 }
                 switch ($reader->name) {
                     case "record":
                         try {
                             $this->cache($harvest, $node);
                         } catch (Exception $e) {
                             JHarvestHelper::log($e->getMessage(), JLog::ERROR);
                         }
                         break;
                     case 'responseDate':
                         // only get the response date if fresh harvest.
                         if (!$resumptionToken) {
                             $this->harvested = JFactory::getDate($node);
                         }
                         break;
                     case 'request':
                         $prefix = JArrayHelper::getValue($attributes, 'metadataPrefix', null, 'string');
                         break;
                     case 'error':
                         if (JArrayHelper::getValue($attributes, 'code', null, 'string') !== "noRecordsMatch") {
                             throw new Exception((string) $node, 500);
                         }
                         break;
                     case 'resumptionToken':
                         $resumptionToken = (string) $node;
                         break;
                     default:
                         break;
                 }
             }
         }
     } while ($resumptionToken);
 }
Beispiel #26
0
 /**
  * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
  *
  * @param   string     $pFilename
  * @throws   PHPExcel_Reader_Exception
  */
 public function listWorksheetInfo($pFilename)
 {
     // Check if file exists
     if (!file_exists($pFilename)) {
         throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
     }
     $worksheetInfo = array();
     $zipClass = PHPExcel_Settings::getZipClass();
     $zip = new $zipClass();
     $zip->open($pFilename);
     $rels = simplexml_load_string($this->securityScan($this->_getFromZipArchive($zip, "_rels/.rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());
     //~ http://schemas.openxmlformats.org/package/2006/relationships");
     foreach ($rels->Relationship as $rel) {
         if ($rel["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument") {
             $dir = dirname($rel["Target"]);
             $relsWorkbook = simplexml_load_string($this->securityScan($this->_getFromZipArchive($zip, "{$dir}/_rels/" . basename($rel["Target"]) . ".rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());
             //~ http://schemas.openxmlformats.org/package/2006/relationships");
             $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships");
             $worksheets = array();
             foreach ($relsWorkbook->Relationship as $ele) {
                 if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet") {
                     $worksheets[(string) $ele["Id"]] = $ele["Target"];
                 }
             }
             $xmlWorkbook = simplexml_load_string($this->securityScan($this->_getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());
             //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
             if ($xmlWorkbook->sheets) {
                 $dir = dirname($rel["Target"]);
                 foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
                     $tmpInfo = array('worksheetName' => (string) $eleSheet["name"], 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0);
                     $fileWorksheet = $worksheets[(string) self::array_item($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")];
                     $xml = new XMLReader();
                     $res = $xml->xml($this->securityScanFile('zip://' . PHPExcel_Shared_File::realpath($pFilename) . '#' . "{$dir}/{$fileWorksheet}"), null, PHPExcel_Settings::getLibXmlLoaderOptions());
                     $xml->setParserProperty(2, true);
                     $currCells = 0;
                     while ($xml->read()) {
                         if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) {
                             $row = $xml->getAttribute('r');
                             $tmpInfo['totalRows'] = $row;
                             $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
                             $currCells = 0;
                         } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) {
                             $currCells++;
                         }
                     }
                     $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
                     $xml->close();
                     $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1;
                     $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']);
                     $worksheetInfo[] = $tmpInfo;
                 }
             }
         }
     }
     $zip->close();
     return $worksheetInfo;
 }
$formatting['bold'] = 'closed';
$formatting['italic'] = 'closed';
$formatting['underline'] = 'closed';
$formatting['header'] = 0;

$for_image = $xmlFile2;
$status = false;
// loop through docx xml dom
while ($reader->read()) {

    // look for new paragraphs
    if ($reader->nodeType == XMLREADER::ELEMENT && $reader->name === 'w:p') {
        // set up new instance of XMLReader for parsing paragraph independantly
        $paragraph = new XMLReader;
        $p = $reader->readOuterXML();
        $paragraph->xml($p);

        // search for heading
        preg_match('/<w:pStyle w:val="(Heading.*?[1-6])"/', $p, $matches);
        switch ($matches[1]) {
            case 'Heading1': $formatting['header'] = 1;
                break;
            case 'Heading2': $formatting['header'] = 2;
                break;
            case 'Heading3': $formatting['header'] = 3;
                break;
            case 'Heading4': $formatting['header'] = 4;
                break;
            case 'Heading5': $formatting['header'] = 5;
                break;
            case 'Heading6': $formatting['header'] = 6;
			<th class='authors'>Authors</th>
		</thead>
		<tbody id='resultsList'>
<?php 
    foreach ($idArray as $id) {
        $record_data = array();
        $authorIndex = 0;
        $urlBase = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=";
        $searchTerm = urlencode($id);
        $url = $urlBase . $searchTerm . "&retmode=xml";
        $curl = curl_init();
        curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url));
        $response = curl_exec($curl);
        // Construct new XMLReader
        $reader = new XMLReader();
        $reader->xml($response);
        // Iterate through the nodes of the XML file
        while ($reader->read()) {
            if ($reader->nodeType == XMLREADER::ELEMENT && array_search($reader->name, $field_keys)) {
                $nodeName = $reader->name;
                $readThrough[] = $nodeName;
                if ($nodeName === "Author") {
                    $authorIndex++;
                }
            }
            if ($reader->nodeType == XMLREADER::END_ELEMENT && array_search($reader->name, $field_keys)) {
                array_pop($readThrough);
                $nodeName = $readThrough[count($readThrough) - 1];
            }
            if ($reader->nodeType == XMLREADER::ELEMENT && count($readThrough) > 0) {
                if (in_array($reader->name, $fieldsArray[$nodeName])) {
Beispiel #29
0
function make_db_cache($username)
{
    $data = array('lastupdate' => time(), 'playcount' => 0, 'statsstart' => 0, 'username' => $username);
    $profile_xml = file_get_contents("http://ws.audioscrobbler.com/1.0/user/" . rawurlencode($username) . "/profile.xml");
    $feed = new XMLReader();
    if ($profile_xml && $feed->xml($profile_xml)) {
        while ($feed->read()) {
            if ($feed->nodeType == XMLReader::ELEMENT) {
                switch ($feed->name) {
                    case "playcount":
                        $feed->read();
                        $data['playcount'] = intval($feed->value);
                        break;
                    case "registered":
                    case "statsreset":
                        $data['statsstart'] = $feed->getAttribute("unixtime");
                        break;
                    case "profile":
                        $data['username'] = $feed->getAttribute("username");
                        break;
                }
            }
        }
        if ($data['playcount'] != 0) {
            $q = sprintf("REPLACE INTO users (lastupdate,playcount,statsstart,username)\n                 VALUES ('%s',%s,'%s','%s');", $data['lastupdate'], $data['playcount'], $data['statsstart'], $username);
            mysql_query($q);
        }
    }
    return $data['playcount'] != 0 ? $data : NULL;
}
Beispiel #30
0
 public function getRecentSMS()
 {
     $html = '';
     $json = '';
     $returnJSON = array();
     $returnJSON['SMS'] = array();
     // $params = $this->getBaseParams();
     $session = $this->getCurlGet($this->gvBaseURL . 'inbox/recent/sms?auth=' . $this->authToken);
     $result = curl_exec($session);
     // echo $result;
     $xml = new XMLReader();
     $xml->xml($result);
     $xml->read();
     if ($xml->name == 'response') {
         $xml->read();
         $xml->next('json');
         if ($xml->name == 'json') {
             $json = $xml->readString();
             $returnJSON['SMS']['data'] = json_decode($json, true);
         }
         $xml->next('html');
         // echo "name: " . $xml->name . " end";
         if ($xml->name == 'html') {
             // echo 'html: ' > $xml->readString();
             // echo "in HTML";
             // echo $xml->readString();
             $html = $xml->readString();
         }
     }
     $returnJSON['SMS']['data']['messagesByNumber'] = array();
     if (strlen($html) > 0) {
         $dom = new DOMDocument();
         // $smsData = array('conversations'=>array());
         if (@$dom->loadHTML($html)) {
             // echo $dom->saveHTML();
             $xpath = new DOMXPath($dom);
             $conversations = $xpath->query('//div[contains(@class, " gc-message ")]');
             $convo = array();
             // for ($citer = 0; $citer < $conversations->length; $citer++) {//$conversations as $conversation) {
             for ($citer = $conversations->length - 1; $citer >= 0; $citer--) {
                 $conversation = $conversations->item($citer);
                 // echo $entry->textContent . '<br>';
                 // echo $conversation->textContent;
                 $conversationID = $conversation->attributes->getNamedItem('id')->value;
                 $contactInfo = $xpath->query('div//a[contains(@class, "gc-message-name-link")]', $conversation);
                 $contactName = $contactInfo->item(0)->textContent;
                 $returnJSON['SMS']['data']['messages'][$conversationID]['contactName'] = $contactName;
                 $contactNumber = $returnJSON['SMS']['data']['messages'][$conversationID]['phoneNumber'];
                 if (!$returnJSON['SMS']['data']['messagesByNumber'][$contactNumber]) {
                     $returnJSON['SMS']['data']['messagesByNumber'][$contactNumber] = array();
                     $returnJSON['SMS']['data']['messagesByNumber'][$contactNumber]['meta'] = array('contactName' => $contactName, 'displayNumber' => $returnJSON['SMS']['data']['messages'][$conversationID]['displayNumber']);
                     $returnJSON['SMS']['data']['messagesByNumber'][$contactNumber]['messages'] = array();
                 }
                 $msgJSON = array('from' => 'TIME_CHANGE', 'text' => $returnJSON['SMS']['data']['messages'][$conversationID]['displayStartDateTime'], 'time' => '');
                 array_push($returnJSON['SMS']['data']['messagesByNumber'][$contactNumber]['messages'], $msgJSON);
                 $messages = $xpath->query('div//div[contains(@class, "gc-message-sms-row")]', $conversation);
                 for ($miter = 0; $miter < $messages->length; $miter++) {
                     // ($messages as $message) {
                     $message = $messages->item($miter);
                     $from = trim($message->childNodes->item(1)->textContent);
                     $text = $message->childNodes->item(3)->textContent;
                     $time = trim($message->childNodes->item(5)->textContent);
                     $messageJSON = array('from' => $from, 'text' => $text, 'time' => $time);
                     array_push($convo, $messageJSON);
                     array_push($returnJSON['SMS']['data']['messagesByNumber'][$contactNumber]['messages'], $messageJSON);
                     // echo "Message: " . $from . " " . $text . " " . $time . "<br>";
                 }
                 // echo "<br><br>";
                 // array_push($smsData['conversations'], $convo);
                 // echo $conversationID;
                 $returnJSON['SMS']['data']['messages'][$conversationID]['messages'] = $convo;
                 $convo = array();
             }
             // $returnJSON['SMS']['data'] = $smsData;
         }
     }
     return json_encode($returnJSON);
 }