/** * @param string $url * @param string $method * @param string $body * * @return FhirResponse */ public function request($url, $method = 'GET', $body = null) { $server_name = null; foreach ($this->servers as $name => $server) { if (substr($url, 0, strlen($server['base_url']))) { $server_name = $name; break; } } $this->applyServerConfig($server_name ? $this->servers[$server_name] : array()); $this->http_client->setUri($url); $this->http_client->setMethod($method); if ($body) { $this->http_client->setRawData($body, 'application/xml+fhir; charset=utf-8'); } $response = $this->http_client->request(); $this->http_client->resetParameters(); if ($body = $response->getBody()) { $use_errors = libxml_use_internal_errors(true); $value = Yii::app()->fhirMarshal->parseXml($body); $errors = libxml_get_errors(); libxml_use_internal_errors($use_errors); if ($errors) { throw new Exception("Error parsing XML response from {$method} to {$url}: " . print_r($errors, true)); } } else { $value = null; } return new FhirResponse($response->getStatus(), $value); }
/** * 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; }
/** * Returns array of simple xml objects, where key is a handle name * * @return SimpleXmlElement[] * @throws RuntimeException in case of load error (malformed xml, etc) */ public function load() { $this->validate(); $original = libxml_use_internal_errors(true); $simpleXmlElement = simplexml_load_file($this->filePath); $errors = libxml_get_errors(); libxml_clear_errors(); libxml_use_internal_errors($original); if ($simpleXmlElement === false) { $messages = array(); foreach ($errors as $error) { $messages[] = sprintf('%s, line %s, column %s', trim($error->message), $error->line, $error->column); } throw new RuntimeException(sprintf('File "%s" has a malformed xml structure: %s', $this->filePath, PHP_EOL . implode(PHP_EOL, $messages))); } $stringXml = array(); // First convert all elements to string, // as in xml file can be multiple string with the same handle names foreach ($simpleXmlElement->children() as $key => $element) { if (!isset($stringXml[$key])) { $stringXml[$key] = ''; } foreach ($element->children() as $child) { $stringXml[$key] .= $child->asXml(); } } $result = array(); foreach ($stringXml as $key => $xml) { $result[$key] = simplexml_load_string(sprintf('<%1$s>%2$s</%1$s>', $key, $xml)); } return $result; }
public function validate($xml,$schema) { // Enable user error handling libxml_use_internal_errors(true); try { if(empty($xml)) { throw new Exception("You provided an empty XML string"); } $doc = DOMDocument::loadXML($xml); if(!($doc instanceof DOMDocument)){ $this->_errors = libxml_get_errors(); } if(!@$doc->schemaValidate($schema)){ $this->_errors = libxml_get_errors(); } } catch (Exception $e) { $this->_errors = array(0 => array('message'=>$e->getMessage())); } // Disable user error handling & Error Cleanup libxml_use_internal_errors(false); libxml_clear_errors(); // If there are no errors, assume that it is all OK! return empty($this->_errors); }
public function runTest() { libxml_use_internal_errors(true); $xml = XMLReader::open(join(DIRECTORY_SEPARATOR, array($this->directory, $this->fileName))); $xml->setSchema(join(DIRECTORY_SEPARATOR, array($this->directory, $this->xsdFilename))); $this->logger->trace(__METHOD__); $this->logger->info(' XML file to test validity is ' . $this->fileName . 'using XSD file ' . $this->xsdFilename); // You have to parse the XML-file if you want it to be validated $currentReadCount = 1; $validationFailed = false; while ($xml->read() && $validationFailed == false) { // I want to break as soon as file is shown not to be valid // We could allow it to collect a few messages, but I think it's best // to do a manual check once we have discovered the file is not // correct. Speed is really what we want here! if ($currentReadCount++ % Constants::XML_PROCESSESING_CHECK_ERROR_COUNT == 0) { if (count(libxml_get_errors()) > 0) { $validationFailed = true; } } } if (count(libxml_get_errors()) == 0) { $this->testProperty->addTestResult(true); $this->logger->info(' RESULT Validation of [' . $this->fileName . '] against [' . $this->xsdFilename . '] succeeded'); $this->testProperty->addTestResultDescription('Validation of [' . $this->fileName . '] against [' . $this->xsdFilename . '] succeeded'); $this->testProperty->addTestResultReportDescription('Filen ' . $this->fileName . ' validerer mot filen' . $this->xsdFilename); } else { $this->testProperty->addTestResult(false); $this->logger->error(' RESULT Validation of [' . $this->fileName . '] against [' . $this->xsdFilename . '] failed'); $this->testProperty->addTestResultDescription('Validation of [' . $this->fileName . '] against [' . $this->xsdFilename . '] failed'); $this->testProperty->addTestResultReportDescription('Filen ' . $this->fileName . ' validerer ikke mot filen' . $this->xsdFilename); } libxml_clear_errors(); }
/** * Method to test the value. * * @param JXMLElement &$element The JXMLElement object representing the <field /> tag for the form field object. * @param mixed $value The form field value to validate. * @param string $group The field name group control value. This acts as as an array container for the field. * For example if the field has name="foo" and the group value is set to "bar" then the * full field name would end up being "bar[foo]". * @param JRegistry &$input An optional JRegistry object with the entire data set to validate against the entire form. * @param object &$form The form object for which the field is being tested. * * @return boolean True if the value is valid, false otherwise. * * @since 11.1 * @throws JException on invalid rule. */ public function test(&$element, $value, $group = null, &$input = null, &$form = null) { if (empty($value)) { return true; } // compatibility workaround: in some environments XML document is // saved with all "<styles>" element opening tags replaced with // "<s-tyles>". We allow this replace (as it can be DB security // concerned: looks like an HTML element <style...) and do not // report error. Later the original element syntax will be restored $value = str_replace('<s-tyles>', '<styles>', $value); // now XML document should be valid jimport('joomla.utilities.xmlelement'); libxml_use_internal_errors(true); $xml = simplexml_load_string($value, 'JXMLElement'); if ($xml === false) { $errors = array(JText::_('MOD_SMARTCDPRO_ERROR_DIGITS_XML_ERROR')); foreach (libxml_get_errors() as $error) { $errors[] = 'XML: ' . $error->message; } $element['message'] = implode('<br />', $errors); return false; } $field = $xml->getName(); if ($field != 'config') { $element['message'] = JText::_('MOD_SMARTCDPRO_ERROR_DIGITS_XML_CONFIG_MISSING'); return false; } if (!$xml->xpath('//digit[@scope="*"]')) { $element['message'] = JText::_('MOD_SMARTCDPRO_ERROR_DIGITS_XML_DEFAULT_DIGIT_MISSING'); return false; } $element['message'] = ''; return true; }
/** * Creates and returns XmlScheme object for addon * * @param string $addon_id Addon name * @param string $path Path to addons * @return AXmlScheme object */ public static function getScheme($addon_id, $path = '') { if (empty($path)) { $path = Registry::get('config.dir.addons'); } libxml_use_internal_errors(true); if (!isset(self::$schemas[$addon_id])) { $_xml = self::readXml($path . $addon_id . '/addon.xml'); if ($_xml !== FALSE) { $versions = self::getVersionDefinition(); $version = isset($_xml['scheme']) ? (string) $_xml['scheme'] : '1.0'; self::$schemas[$addon_id] = new $versions[$version]($_xml); } else { $errors = libxml_get_errors(); $text_errors = array(); foreach ($errors as $error) { $text_errors[] = self::displayXmlError($error, $_xml); } libxml_clear_errors(); if (!empty($text_errors)) { fn_set_notification('E', __('xml_error'), '<br/>' . implode('<br/>', $text_errors)); } return false; } } return self::$schemas[$addon_id]; }
/** * Check a given XML file against the DRV rules * * @param string $pathToFile full path to the XML file * @return bool if there were any errors during processing */ private function is_valid_drv_file($pathToFile) { $hasErrors = false; // Enable user error handling libxml_use_internal_errors(true); $xml = new \DOMDocument(); $xml->load($pathToFile); $pathToSchema = realpath($this->get('kernel')->getRootDir() . '/Resources/drv_import/meldungen_2010.xsd'); if (!file_exists($pathToSchema)) { $message = 'Konnte DRV-Schema auf Server nicht finden!'; $this->addFlash('error', $message); $this->get('logger')->warning($message . ' Gesuchter Pfad: ' . $pathToSchema); $hasErrors = true; } if (!$hasErrors && !$xml->schemaValidate($pathToSchema)) { if (self::DRV_DEBUG) { print '<b>DOMDocument::schemaValidate() generated Errors!</b>' . "\n"; $errors = libxml_get_errors(); libxml_clear_errors(); foreach ($errors as $error) { print '<<<<<<<<<<<<<<<<<<<<<<<<<' . "\n"; print $this->libxml_display_error($error); print_r($error); print '>>>>>>>>>>>>>>>>>>>>>>>>>' . "\n"; } } else { $this->addFlash('error', 'Nur XML-Export-Dateien vom DRV sind erlaubt!'); $hasErrors = true; } } return $hasErrors; }
function show_internal_errors() { foreach (libxml_get_errors() as $error) { printf("Internal: %s\n", $error->message); } libxml_clear_errors(); }
/** * Fetch error for current parser * * @access protected * @return string the error message */ protected function getParserError() { $errors = ''; foreach (libxml_get_errors() as $error) { $return = ''; switch ($error->level) { case LIBXML_ERR_WARNING: $return .= "Warning {$error->code}: "; break; case LIBXML_ERR_ERROR: $return .= "Error {$error->code}: "; break; case LIBXML_ERR_FATAL: $return .= "Fatal Error {$error->code}: "; break; } $return .= trim($error->message) . PHP_EOL . " Line: {$error->line}" . PHP_EOL . " Column: {$error->column}"; if ($error->file) { $return .= PHP_EOL . " File: {$error->file}"; } #combine with other error messages $errors .= PHP_EOL . $return; } return $errors; }
/** * Initialize DOM document */ public function initDomDocument() { if (null === ($document = $this->getDocument())) { #require_once 'Zend/Dom/Exception.php'; throw new Zend_Dom_Exception('Cannot query; no document registered'); } libxml_use_internal_errors(true); $this->_domDocument = new DOMDocument(); switch ($this->getDocumentType()) { case self::DOC_XML: $success = $this->_domDocument->loadXML($document); break; case self::DOC_HTML: case self::DOC_XHTML: default: $success = $this->_domDocument->loadHTML($document); break; } $errors = libxml_get_errors(); if (!empty($errors)) { $this->_documentErrors = $errors; libxml_clear_errors(); } libxml_use_internal_errors(false); if (!$success) { #require_once 'Zend/Dom/Exception.php'; throw new Zend_Dom_Exception(sprintf('Error parsing document (type == %s)', $this->getDocumentType())); } return $this; }
protected function processXML($input) { try { if (!isset($input[2])) { throw new Exception("Invalid Input"); } libxml_use_internal_errors(true); // convert the xml into Object $inputObject = simplexml_load_string($input, "SimpleXMLElement", LIBXML_NOCDATA); if (!$inputObject) { // @var Array to store the error messages $errors = array(); // loop through the errors and store the errors in $errors foreach (libxml_get_errors() as $e) { $errors[] = $e->message; } // @var String Errors are joined by a newline $errors = join("\n", $errors); // throw the error throw new Exception($errors); } // if !$inputObject foreach ($inputObject as $name => $value) { $val = strtolower(trim($value)) == '(null)' ? '' : trim($value); $inputObject->{$name} = $val; } return $inputObject; } catch (Exception $e) { $this->setError($e->getMessage()); } }
/** * Import the xml document from the stream into the repository * * @param NodeInterface $parentNode as in importXML * @param NamespaceRegistryInterface $ns as in importXML * @param string $uri as in importXML * @param integer $uuidBehavior as in importXML * * @see PHPCR\SessionInterface::importXML */ public static function importXML(NodeInterface $parentNode, NamespaceRegistryInterface $ns, $uri, $uuidBehavior) { $use_errors = libxml_use_internal_errors(true); libxml_clear_errors(); if (!file_exists($uri)) { throw new \RuntimeException("File {$uri} does not exist or is not readable"); } $xml = new FilteredXMLReader(); $xml->open($uri); if (libxml_get_errors()) { libxml_use_internal_errors($use_errors); throw new InvalidSerializedDataException("Invalid xml file {$uri}"); } $xml->read(); try { if ('node' == $xml->localName && NamespaceRegistryInterface::NAMESPACE_SV == $xml->namespaceURI) { // TODO: validate with DTD? self::importSystemView($parentNode, $ns, $xml, $uuidBehavior); } else { self::importDocumentView($parentNode, $ns, $xml, $uuidBehavior); } } catch (\Exception $e) { // restore libxml setting libxml_use_internal_errors($use_errors); // and rethrow exception to not hide it throw $e; } libxml_use_internal_errors($use_errors); }
/** * Create a PHP array from the XML file * * @param String $xmlFile The XML file or a string containing xml to parse * * @return Array * * @throws \Propel\Common\Config\Exception\XmlParseException if parse errors occur */ public static function convert($xmlToParse) { if (!is_string($xmlToParse)) { throw new InvalidArgumentException("XmlToArrayConverter::convert method expects an xml file to parse, or a string containing valid xml"); } if (file_exists($xmlToParse)) { $xmlToParse = file_get_contents($xmlToParse); } //Empty xml file returns empty array if ('' === $xmlToParse) { return array(); } if ($xmlToParse[0] !== '<') { throw new InvalidArgumentException('Invalid xml content'); } $currentEntityLoader = libxml_disable_entity_loader(true); $currentInternalErrors = libxml_use_internal_errors(true); $xml = simplexml_load_string($xmlToParse); $errors = libxml_get_errors(); libxml_clear_errors(); libxml_use_internal_errors($currentInternalErrors); libxml_disable_entity_loader($currentEntityLoader); if (count($errors) > 0) { throw new XmlParseException($errors); } $conf = self::simpleXmlToArray($xml); return $conf; }
/** * Convert xml string to SimpleXMLElement * * @param string $data String of retrieved data * * @return \SimpleXMLElement * @throws XmlException */ public static function getXml($data) { if (self::$libXmlLoaded === null) { self::$libXmlLoaded = extension_loaded('libxml'); } if (self::$libXmlLoaded) { libxml_use_internal_errors(true); } $simpleXml = simplexml_load_string($data); if (!$simpleXml) { if (self::$libXmlLoaded) { $xmlErrors = libxml_get_errors(); $errors = array(); foreach ($xmlErrors as $error) { $errors[] = sprintf('Error in file %s on line %d with message : %s', $error->file, $error->line, $error->message); } if (count($errors) > 0) { throw new XmlException(implode("\n", $errors)); } } // @codeCoverageIgnore throw new XmlException('Xml file cound not be loaded.'); } return $simpleXml; }
/** * @param \Jarves\Configuration\Object[] $objects * @param OutputInterface $output * * @param bool $overwrite * @throws ModelBuildException */ public function build(array $objects, OutputInterface $output, $overwrite = false) { /** @var $jarves \Jarves\Jarves */ $jarves = $this->kernel->getContainer()->get('jarves'); $output->writeln('Propel Build'); foreach ($objects as $object) { if ($this->kernel->getContainer()->get($object->getStorageService()) instanceof \Jarves\Storage\Propel) { $output->write('Build object ' . $object->getId() . ' => ' . $object->getTable() . ' ... '); $bundlePath = $jarves->getBundleDir($object->getBundle()->getName()); $modelsFile = sprintf('%sResources/config/schema/%s.schema.xml', $bundlePath, strtolower($object->getTable())); if (!$overwrite && file_exists($modelsFile) && file_get_contents($modelsFile)) { $xml = @simplexml_load_file($modelsFile); if (false === $xml) { $errors = libxml_get_errors(); throw new ModelBuildException(sprintf('Parse error in %s: %s', $modelsFile, json_encode($errors, JSON_PRETTY_PRINT))); } } else { $xml = simplexml_load_string('<database></database>'); } $xml['namespace'] = $object->getBundle()->getNamespace() . '\\Model'; // $xml['package'] = $object->getBundle()->getNamespace() . '\\Model'; $xml['name'] = 'default'; $this->declareTable($xml, $object); if (!is_dir(dirname($modelsFile))) { mkdir(dirname($modelsFile), 0777, true); } file_put_contents($modelsFile, $this->getFormattedXml($xml)); $output->writeln($modelsFile . ' written.'); unset($xml); } } }
public static function import_xml($file) { $defaults = array('forms' => 0, 'fields' => 0, 'terms' => 0); $imported = array('imported' => $defaults, 'updated' => $defaults, 'forms' => array()); unset($defaults); if (!defined('WP_IMPORTING')) { define('WP_IMPORTING', true); } if (!class_exists('DOMDocument')) { return new WP_Error('SimpleXML_parse_error', __('Your server does not have XML enabled', 'formidable'), libxml_get_errors()); } $dom = new DOMDocument(); $success = $dom->loadXML(file_get_contents($file)); if (!$success) { return new WP_Error('SimpleXML_parse_error', __('There was an error when reading this XML file', 'formidable'), libxml_get_errors()); } $xml = simplexml_import_dom($dom); unset($dom); // halt if loading produces an error if (!$xml) { return new WP_Error('SimpleXML_parse_error', __('There was an error when reading this XML file', 'formidable'), libxml_get_errors()); } // add terms, forms (form and field ids), posts (post ids), and entries to db, in that order // grab cats, tags and terms if (isset($xml->term)) { $imported = self::import_xml_terms($xml->term, $imported); unset($xml->term); } if (isset($xml->form)) { $imported = self::import_xml_forms($xml->form, $imported); unset($xml->form); } $return = apply_filters('frm_importing_xml', $imported, $xml); return $return; }
public function __construct($strConfigSet = "") { libxml_use_internal_errors(); $this->objSimpleXml = simplexml_load_file(SVN2RSS_PROJECT_ROOT . "/" . SVN2RSS_CONFIG_FILE); $arrParseErrors = libxml_get_errors(); libxml_clear_errors(); if (count($arrParseErrors) > 0) { throw new Svn2RssException("Error parsing xml-config-file " . SVN2RSS_CONFIG_FILE . ".\nErrors:\n" . implode("\n", $arrParseErrors)); } if ($strConfigSet == "") { $strConfigSet = $this->getStrDefaultConfigSet(); } if ($strConfigSet == "") { throw new Svn2RssException("No default config-set defined in " . SVN2RSS_CONFIG_FILE); } //load the config-set requested $this->strConfigSetName = $strConfigSet; foreach ($this->objSimpleXml->configSets->configSet as $objOneConfigSet) { $arrAttributes = $objOneConfigSet->attributes(); if ($arrAttributes->id . "" == $strConfigSet) { $this->objCurrentConfigSetXml = $objOneConfigSet; } } if ($this->objCurrentConfigSetXml == null) { throw new Svn2RssException("Loading of config set " . $strConfigSet . " failed."); } }
public function getPinterest() { $url = 'http://www.pinterest.com/wheatwildflower/feed.rss'; if (($response_xml_data = file_get_contents($url)) === false) { echo "Error fetching XML\n"; die; } else { libxml_use_internal_errors(true); $data = simplexml_load_string($response_xml_data); if (!$data) { echo "Error loading XML\n"; die; foreach (libxml_get_errors() as $error) { echo "\t", $error->message; } } else { $json = array(); $json['imgs'] = array(); foreach ($data as $channel) { foreach ($channel as $pin) { if ((string) $pin->description) { $doc = new DOMDocument(); $doc->loadHTML((string) $pin->description[0]); $pinHTML = $pin->description[0]; $img = substr($pinHTML, strpos($pinHTML, "src=") + 5, strpos($pinHTML, ".jpg") + 5 - (strpos($pinHTML, "src=") + 6)); $json['imgs'][] = $img; } } } header('Content-Type: application/json'); echo json_encode($json); die; } } }
public function testLoadFileWithInternalErrorsEnabled() { libxml_use_internal_errors(true); $this->assertSame(array(), libxml_get_errors()); $this->assertInstanceOf('DOMDocument', XmlUtils::loadFile(__DIR__ . '/../Fixtures/Util/invalid_schema.xml')); $this->assertSame(array(), libxml_get_errors()); }
/** * Checks to see if some XML is valid * @param string $string as a string. * @return boolean true if the XML appears valid. */ private function isValidXml($string) { $orig_error_setting = libxml_use_internal_errors(true); // See security note elsewhere in this file and http://php.net/manual/en/function.libxml-disable-entity-loader.php // Supported from 5.2.11, so allow for older versions to work as well. if (function_exists('libxml_disable_entity_loader')) { $original_el_setting = libxml_disable_entity_loader(false); } // Suppress anything PHP might moan about. $temp = @simplexml_load_string($string); $ok = false; if (!$temp) { $errors = array(); foreach (libxml_get_errors() as $libXMLError) { $errors[] = $libXMLError->file . ' : line ' . $libXMLError->line . ', col:' . $libXMLError->column . ', message:' . $libXMLError->message; } libxml_clear_errors(); _debug("Error detected in XML : " . implode(',', $errors)); $ok = false; } else { $ok = true; } if (function_exists('libxml_disable_entity_loader')) { libxml_disable_entity_loader($original_el_setting); } libxml_use_internal_errors($orig_error_setting); return $ok; }
public static function process_libxml_errors() { $error_queue = array(); $errors = libxml_get_errors(); foreach ($errors as $i => &$error) { if (isset($error_queue[$error->line])) { // There's already been an error reported for this line unset($errors[$i]); } switch ($error->code) { case 1840: // Not in enumeration // Not in enumeration case 1839: // Not in pattern // Not in pattern case 1871: // Missing / invalid element // Missing / invalid element case 1833: // Below the minInclusive value echo PHP_EOL . $error->message; echo 'Line ' . $error->line . ': ' . $error->file . PHP_EOL; $error_queue[$error->line] = true; unset($errors[$i]); break; } } if (count($errors) > 0 && PTS_IS_CLIENT) { // DEBUG print_r($errors); } libxml_clear_errors(); }
public function parseIt() { libxml_use_internal_errors(true); $this->load(); $this->page = str_replace('xmlns=', 'ns=', $this->page); try { $this->xml = new SimpleXMLElement($this->page); } catch (Exception $e) { echo "<pre>"; foreach (libxml_get_errors() as $error) { if ($error->level == LIBXML_ERR_WARNING) { echo "Warning: " . $error->message; } if ($error->level == LIBXML_ERR_ERROR) { echo "Error: " . $error->message; } if ($error->level == LIBXML_ERR_FATAL) { echo "Fatal error: " . $error->message; } } echo "</pre>"; echo $this->page; return; } }
/** * Returns an array of search suggestions from the unofficial completion API located * at the endpoint specified in this class. &q=query * * Parses the output into an array of associative arrays with keys of term, volume and * current. "current" is a boolean that determines whether the result in question is the searched * for term. * * @return array|WP_Error WP_Error if something goes wrong. Otherwise, an array as described above. */ public static function get_suggestions($search_term) { $search_term = trim($search_term); if (empty($search_term)) { return new WP_Error('empty_term', __('Please provide a search term.', 'scribeseo')); } $response = wp_remote_get(add_query_arg(array('q' => urlencode($search_term)), self::ENDPOINT)); if (is_wp_error($response)) { return $response; } $result = array(); // turn on user error handing $user_errors = libxml_use_internal_errors(true); $complete_suggestions = simplexml_load_string(wp_remote_retrieve_body($response)); // get any errors $xml_errors = libxml_get_errors(); // restore error handling setting libxml_use_internal_errors($user_errors); if (!empty($xml_errors)) { return new WP_Error('xml_error', __('The XML from the Google Completion API could not be loaded appropriately.', 'scribeseo')); } $complete_suggestions_po = json_decode(json_encode($complete_suggestions)); if (!is_object($complete_suggestions_po) || !isset($complete_suggestions_po->CompleteSuggestion)) { return new WP_Error('xml_error', __('The XML from the Google Completion API could not be loaded appropriately.', 'scribeseo')); } foreach ($complete_suggestions_po->CompleteSuggestion as $suggestion) { $term = $suggestion->suggestion->{'@attributes'}->data; $volume = intval($suggestion->num_queries->{'@attributes'}->int); $volume_nice = number_format_i18n($volume); $current = $term == $search_term; $result[] = compact('term', 'volume', 'volume_nice', 'current'); } return $result; }
public static function get_parser($data, $url = false, $debug = false) { libxml_use_internal_errors(true); $data = trim($data); $xml = @simplexml_load_string($data, null, LIBXML_DTDLOAD); if (!$xml) { if ($debug) { echo "******** RSS PARSING ERROR: XML could not be loaded ********\n"; foreach (libxml_get_errors() as $error) { printf("Error %d on line %d, column %d, level %d\n %s", $error->code, $error->line, $error->column, $error->level, $error->message); } } return false; } if ($xml->getName() == "feed") { $rss = new Atom($xml, $debug); $rss->set_url($url); return $rss; } if ($xml->getName() == "rss") { if ($xml['version'] == "2.0") { $rss = new Rss20($xml, $debug); $rss->set_url($url); return $rss; } } if ($debug) { printf("******** RSS PARSING ERROR: %s/%s ********\n", $xml->getName(), $xml['version']); } return false; }
/** * Validate XML to be valid for import * @param string $xml * @param WP_Error[optional] $errors * @return bool Validation status */ public static function validateXml(&$xml, $errors = NULL) { if (FALSE === $xml or '' == $xml) { $errors and $errors->add('form-validation', __('WP All Import can\'t read your file.<br/><br/>Probably, you are trying to import an invalid XML feed. Try opening the XML feed in a web browser (Google Chrome is recommended for opening XML files) to see if there is an error message.<br/>Alternatively, run the feed through a validator: http://validator.w3.org/<br/>99% of the time, the reason for this error is because your XML feed isn\'t valid.<br/>If you are 100% sure you are importing a valid XML feed, please contact WP All Import support.', 'wp_all_import_plugin')); } else { PMXI_Import_Record::preprocessXml($xml); if (function_exists('simplexml_load_string')) { libxml_use_internal_errors(true); libxml_clear_errors(); $_x = @simplexml_load_string($xml); $xml_errors = libxml_get_errors(); libxml_clear_errors(); if ($xml_errors) { $error_msg = '<strong>' . __('Invalid XML', 'wp_all_import_plugin') . '</strong><ul>'; foreach ($xml_errors as $error) { $error_msg .= '<li>'; $error_msg .= __('Line', 'wp_all_import_plugin') . ' ' . $error->line . ', '; $error_msg .= __('Column', 'wp_all_import_plugin') . ' ' . $error->column . ', '; $error_msg .= __('Code', 'wp_all_import_plugin') . ' ' . $error->code . ': '; $error_msg .= '<em>' . trim(esc_html($error->message)) . '</em>'; $error_msg .= '</li>'; } $error_msg .= '</ul>'; $errors and $errors->add('form-validation', $error_msg); } else { return true; } } else { $errors and $errors->add('form-validation', __('Required PHP components are missing.', 'wp_all_import_plugin')); $errors and $errors->add('form-validation', __('WP All Import requires the SimpleXML PHP module to be installed. This is a standard feature of PHP, and is necessary for WP All Import to read the files you are trying to import.<br/>Please contact your web hosting provider and ask them to install and activate the SimpleXML PHP module.', 'wp_all_import_plugin')); } } return false; }
/** * Append current XML errors to the the current stack level. */ private static function addErrors() { $currentErrors = libxml_get_errors(); libxml_clear_errors(); $level = count(self::$errorStack) - 1; self::$errorStack[$level] = array_merge(self::$errorStack[$level], $currentErrors); }
function openxml($filepath, &$error_str = false) { $xmlstr = @file_get_contents($filepath); if ($xmlstr == false) { $error_str = "failed to open file {$filepath}"; return false; } $options = LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_ERR_NONE | LIBXML_COMPACT; $xmldoc = new DOMDocument(); $xmldoc->strictErrorChecking = false; $xmldoc->recover = true; $old = error_reporting(0); $old_libxml = libxml_use_internal_errors(true); $ret = @$xmldoc->loadXml($xmlstr, $options); if ($ret == false) { $error_str = "failed to load xml from {$filepath}"; return false; } $errors = libxml_get_errors(); if (count($errors) > 0) { foreach ($errors as $error) { if ($error->level == LIBXML_ERR_FATAL) { $error_str = "file: {{$filepath}} line: {$error->line} column: {$error->column}: fatal error: {$error->code}: {$error->message}"; return false; } } } $xml = @simplexml_import_dom($xmldoc); error_reporting($old); libxml_use_internal_errors($old_libxml); return $xml; }
public function request(Neostrada_Domain $domain, $action, array $rawParams = []) { $params = ['domain' => $domain->getName(), 'extension' => $domain->getExtension()] + $rawParams; $params['api_sig'] = $this->_calculateSignature($action, $params); $params['action'] = $action; $params['api_key'] = $this->_key; $url = self::API_HOST . '?' . http_build_query($params, '', '&'); $c = curl_init(); if ($c === false) { throw new \RuntimeException('Could not initialize cURL'); } curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($c, CURLOPT_URL, $url); curl_setopt($c, CURLOPT_HEADER, 0); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $rawData = curl_exec($c); if ($rawData === false) { throw new \RuntimeException('Could not complete cURL request: ' . curl_error($c)); } curl_close($c); $oldUseErrors = libxml_use_internal_errors(true); $xml = simplexml_load_string($rawData); if ($xml === false) { $message = libxml_get_errors()[0]->message; libxml_use_internal_errors($oldUseErrors); throw new \RuntimeException('Invalid XML: ' . $message); } libxml_use_internal_errors($oldUseErrors); $this->_validateResponse($xml); return $xml; }
/** * Create an Array from XML * * This method sets up the SimpleXMLIterator and starts the parsing * of an xml body to iterate through it and transform it into * an array that can be used by the developers. * * @param string $xml * @return array An array mapped to the passed xml */ public static function arrayFromXml($xml) { // replace namespace defs $xml = str_replace('xmlns=', 'ns=', $xml); // catch libxml errors libxml_use_internal_errors(true); try { $iterator = new SimpleXMLIterator($xml); } catch(Exception $e) { $xmlErrors = libxml_get_errors(); return new Frapi_Exception( 'Xml Parsing Failed', 'INVALID_XML', 400, 'xml_parsing' ); libxml_clear_errors(); } $xmlRoot = $iterator->getName(); $type = $iterator->attributes()->type; // SimpleXML provides the root information on construct self::$_xmlRoot = $iterator->getName(); self::$_responseType = $type; // return the mapped array with the root element as the header return array($xmlRoot => self::_iteratorToArray($iterator)); }