protected function assertMatchesXpath($html, $expression, $count = 1) { $dom = new \DomDocument('UTF-8'); try { // Wrap in <root> node so we can load HTML with multiple tags at // the top level $dom->loadXml('<root>'.$html.'</root>'); } catch (\Exception $e) { return $this->fail(sprintf( "Failed loading HTML:\n\n%s\n\nError: %s", $html, $e->getMessage() )); } $xpath = new \DOMXPath($dom); $nodeList = $xpath->evaluate('/root'.$expression); if ($nodeList->length != $count) { $dom->formatOutput = true; $this->fail(sprintf( "Failed asserting that \n\n%s\n\nmatches exactly %s. Matches %s in \n\n%s", $expression, $count == 1 ? 'once' : $count . ' times', $nodeList->length == 1 ? 'once' : $nodeList->length . ' times', // strip away <root> and </root> substr($dom->saveHTML(), 6, -8) )); } }
/** * Parse the given xml definition string and return a * Console_CommandLine instance constructed with the xml data. * * @param string $xmlstr the xml string to parse * * @return object a Console_CommandLine instance * @access public * @static */ public static function parseString($xmlstr) { $doc = new DomDocument(); $doc->loadXml($xmlstr); self::validate($doc); $root = $doc->childNodes->item(0); return self::_parseCommandNode($root, true); }
private function parseString($xmlStr) { $document = new DomDocument(); try { $document->loadXml($xmlStr); } catch (Exception $ex) { } return new XmlDataType($document); }
/** * Parses the given xml definition string and returns a * Console_CommandLine instance constructed with the xml data. * * @param string $xmlstr The xml string to parse * * @return Console_CommandLine A parser instance */ public static function parseString($xmlstr) { $doc = new DomDocument(); $doc->loadXml($xmlstr); self::validate($doc); $nodes = $doc->getElementsByTagName('command'); $root = $nodes->item(0); return self::_parseCommandNode($root, true); }
public function prettyPrint($code, $lang) { switch ($lang) { case 'json': return json_encode(json_decode($code), JSON_PRETTY_PRINT); case 'xml': $xml = new \DomDocument('1.0'); $xml->preserveWhiteSpace = false; $xml->formatOutput = true; $xml->loadXml($code); return $xml->saveXml(); default: return $code; } }
public static function unmarshalRoot($string) { $dom = new \DomDocument(); $dom->loadXml($string); $xpath = new \DomXPath($dom); $query = "child::*"; $childs = $xpath->query($query); $binding = array(); foreach ($childs as $child) { $legko = new Bind(); $lDom = new \DomDocument(); $lDom->appendChild($lDom->importNode($child, true)); $binding = $legko->unmarshal($lDom->saveXml()); } return $binding; }
public function parse($content, __Configuration &$configuration) { libxml_use_internal_errors(true); $dom = new DomDocument("1.0"); $dom->loadXml($content); if ($dom->documentElement != null) { $this->_parseDomNode($dom->documentElement, $configuration); } else { $xml_content_array = preg_split('/[\\n\\r]+/', $content); $parse_errors = libxml_get_errors(); $error_descriptions_array = array(); foreach ($parse_errors as $_parse_error) { $error_descriptions_array[] = $this->_getReadableXMLErrorDescription($_parse_error, $xml_content_array); } $error_description = join("\n", $error_descriptions_array); libxml_clear_errors(); throw new __ConfigurationException($error_description); } }
/** * Parse the response XML into an associative array of values. * * @param string response XML */ protected function parseResponse($xml) { $dom = new \DomDocument(); try { // Munge errors into exceptions set_error_handler('\\Pway\\Response::domErrorHandler'); $dom->loadXml($xml); restore_error_handler(); } catch (\DomException $e) { $this->error = self::ERROR_XML; $this->errorMessage = $e->getMessage(); } if ($this->error) { return false; } foreach ($dom->firstChild->childNodes as $node) { $this->responseData[$node->nodeName] = $node->nodeValue; } }
/** * Fetches the necessary attribute information for * the defined media item. * * @return bool */ protected function fetchAttributes() { if (ini_get('allow_url_fopen')) { $youtubeXml = @file_get_contents($this->apiUrl . '/' . $this->mediaId); if (isset($http_response_header) && strpos($http_response_header[0], '200') === false) { throw new ExternalMediaDriver_InvalidID('YouTube ID "' . $this->mediaId . '" does not exist'); } $dom = new DomDocument(); $dom->loadXml($youtubeXml); $xPath = new DomXPath($dom); // Gather all details $group = $xPath->query('//media:group')->item(0); $this->attributes['title'] = $xPath->query('media:title', $group)->item(0)->nodeValue; $this->attributes['description'] = $xPath->query('media:description', $group)->item(0)->nodeValue; $this->attributes['videoUrl'] = $xPath->query('media:content/@url[starts-with(., "http")]', $group)->item(0)->value; $this->attributes['thumbUrl'] = $xPath->query('media:thumbnail[position()=1]/@url', $group)->item(0)->value; return true; } else { return false; } }
/** * Generate and return the OsmChange XML required to record the changes * made to the object in question. * * @return string * @link http://wiki.openstreetmap.org/wiki/OsmChange */ public function getOsmChangeXml() { $type = $this->getType(); if ($this->dirty) { $version = $this->getVersion(); $version++; $domd = new DomDocument(); $domd->loadXml($this->getXml()); $xpath = new DomXPath($domd); $nodelist = $xpath->query("//{$type}"); $nodelist->item(0)->setAttribute('action', $this->action); $nodelist->item(0)->setAttribute('id', $this->getId()); if (!is_null($this->changesetId)) { $nodelist->item(0)->setAttribute('changeset', $this->changesetId); } $tags = $xpath->query("//{$type}/tag"); $set = array(); for ($i = 0; $i < $tags->length; $i++) { $key = $tags->item($i)->getAttribute('k'); $val = $tags->item($i)->getAttribute('v'); $set[$key] = $val; } $diff = array_diff($this->getTags(), $set); // Remove existing tags for ($i = 0; $i < $tags->length; $i++) { $rkey = $tags->item($i)->getAttribute('k'); if (isset($diff[$rkey])) { $nodelist->item(0)->removeChild($tags->item($i)); } } foreach ($diff as $key => $value) { $new = $domd->createElement('tag'); $new->setAttribute('k', $key); $new->setAttribute('v', $value); $nodelist->item(0)->appendChild($new); } $xml = $domd->saveXml($nodelist->item(0)); $xml = "<{$this->action}>{$xml}</{$this->action}>"; return $this->osmChangeXml($xml); } elseif ($this->action == 'delete') { $xml = null; $domd = new DomDocument(); $domd->loadXml($this->getXml()); $xpath = new DomXPath($domd); $n = $xpath->query("//{$type}"); $version = $this->getVersion(); $version++; if (!is_null($this->changesetId)) { $n->item(0)->setAttribute('changeset', $this->changesetId); } $n->item(0)->setAttribute('action', 'delete'); $xml = $domd->saveXml($n->item(0)); return $this->osmChangeXml("<delete>{$xml}</delete>"); } }
function saveXML($simplexml) { global $config; $domDoc = new DomDocument('1.0', 'utf-8'); $domDoc->formatOutput = true; $domDoc->preserveWhiteSpace = false; $domDoc->loadXml($simplexml->asXml()); return file_put_contents($config['xml_tv'], $domDoc->saveXml()); }
/** * Amend osmChangeXml with specific updates pertinent to this Way object. * * @param string $xml OSM Change XML as generated by getOsmChangeXml * * @return string * @see getOsmChangeXml * @link http://wiki.openstreetmap.org/wiki/OsmChange */ public function osmChangeXml($xml) { if ($this->dirtyNodes) { $domd = new DomDocument(); $domd->loadXml($xml); $xpath = new DomXPath($domd); $nodelist = $xpath->query('//' . $this->action . '/way'); $nd = $xpath->query("//{$this->action}/way/nd"); // Remove nodes if appropriate. for ($i = 0; $i < $nd->length; $i++) { $ref = $nd->item($i)->getAttribute('ref'); if (array_search($ref, $this->nodes) === false) { $nodelist->item(0)->removeChild($nd->item($i)); } } // Add new nodes. foreach ($this->nodesNew as $new) { $el = $domd->createElement('nd'); $el->setAttribute('ref', $new); $nodelist->item(0)->appendChild($el); } // Remove blank lines in XML - minimise bandwidth usage. return preg_replace("/(^[\r\n]*|[\r\n]+)[\\s\t]*[\r\n]+/", '', $domd->saveXml($nodelist->item(0))); return $domd->saveXml($nodelist->item(0)); } else { return $xml; } }
/** * Performs a Plesk API request, returns raw API response text * * @param string $packet * * @return string * @throws ApiRequestException */ private function sendRequest($packet) { $domdoc = new \DomDocument('1.0', 'UTF-8'); if ($domdoc->loadXml($packet) === false) { $this->error = 'Failed to load payload'; return false; } $body = $domdoc->saveHTML(); return $this->http->sendRequest($body); }
public static function fromString($xmlString) { $xml = new \DomDocument('1.0', 'UTF-8'); $xml->loadXml($xmlString); return new self($xml); }
/** * Sets up a domdocument for the functions. * * @return DomDocument * The domdocument to modify */ protected function getDom() { if (isset($this->datastream->content) && $this->autoCommit) { // @todo Proper exception handling. $document = new DomDocument(); $document->preserveWhiteSpace = FALSE; $document->loadXml($this->datastream->content); } else { if (!is_null($this->domCache) && !$this->autoCommit) { $document = $this->domCache; } else { $document = new DomDocument("1.0", "UTF-8"); $rootelement = $document->createElement('rdf:RDF'); $document->appendChild($rootelement); } } // Setup the default namespace aliases. foreach ($this->namespaces as $alias => $uri) { // if we use setAttributeNS here we drop the rdf: from about which // breaks things, so we do this, then the hack below. $document->documentElement->setAttribute("xmlns:{$alias}", $uri); } // this is a hack, but it makes sure namespaces are properly registered $document_namespaces = new DomDocument(); $document_namespaces->preserveWhiteSpace = FALSE; $document_namespaces->loadXml($document->saveXML()); return $document_namespaces; }
/** * Load the metadata xml specification * * @param string The base path to read the xml file from * @return boolean (True if all ok, False in other case) */ private function _loadMetadata() { $return_value = array('mapping' => array(), 'autoloaders' => array(), 'classpaths' => array()); #by default //Find any include path files recursively, under the base directory's lib directories if (is_dir($this->_normalized_basedir . DIRECTORY_SEPARATOR . 'libs')) { $includepath_files = __FileResolver::resolveFiles($this->_normalized_basedir . DIRECTORY_SEPARATOR . 'libs' . DIRECTORY_SEPARATOR . '...' . DIRECTORY_SEPARATOR . self::INCLUDE_PATH_FILENAME); } else { $includepath_files = array(); } //Do an explicit check in the baseDir/config directory if (is_file($this->_normalized_basedir . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . self::INCLUDE_PATH_FILENAME)) { $includepath_files[] = $this->_normalized_basedir . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . self::INCLUDE_PATH_FILENAME; } //Go through each include file that we found, and parse the information. foreach ($includepath_files as $includepath_file) { libxml_use_internal_errors(true); $content = file_get_contents($includepath_file); $dom = new DomDocument("1.0"); $dom->loadXml($content); if ($dom->documentElement != null) { foreach ($dom->documentElement->childNodes as $child) { if ($child->nodeName == 'cluster') { if (substr($child->getAttribute('path'), 0, 1) == '/') { $current_dir = $this->_normalized_basedir . DIRECTORY_SEPARATOR; } else { $current_dir = rtrim(dirname($includepath_file), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } $path = trim($child->getAttribute('path')); $path = preg_replace('/\\/\\.\\.\\.$/', '', $path, 1, $count); if ($count == 1) { $recursive = true; } else { $recursive = false; } $current_dir .= ltrim($path, '/'); foreach ($child->childNodes as $class_child) { if ($class_child->nodeName == 'class' || $class_child->nodeName == 'interface') { if (strpos($class_child->getAttribute('name'), '*') !== false) { $class_data = $this->_loadMetaClassesFromMappingRule($class_child, $current_dir, $recursive); $return_value['mapping'] = $class_data + $return_value['mapping']; } else { $class_data = $this->_loadMetaClass($class_child, $current_dir); $return_value['mapping'][strtoupper($class_child->getAttribute('name'))] = $class_data; } } } } else { if ($child->nodeName == 'autoload') { if ($child->hasAttribute('class') && $child->hasAttribute('method')) { $return_value['autoloaders'][$child->getAttribute('class')] = $child->getAttribute('method'); } else { throw new Exception('Missing information to register the autoload method. It was expected a class and a method attribute.'); } } else { if ($child->nodeName == 'classpath') { if ($child->hasAttribute('path')) { $return_value['classpaths'][] = $child->getAttribute('path'); } else { throw new Exception('Missing path attribute.'); } } } } } } else { /** * @todo extract error loading classes location by ussing libxml_get_errors() */ throw new Exception("Error parsing includepath file: " . $includepath_file); } } return $return_value; }
[expect php] [file] <?php function __xml_norm($str) { $str = str_replace(" /", "/", $str); if ($str[strlen($str) - 1] != "\n") { return $str . "\n"; } else { return $str; } } $dom1 = new DomDocument('1.0', 'UTF-8'); $xml = '<foo />'; $dom1->loadXml($xml); $node = clone $dom1->documentElement; $dom2 = new DomDocument('1.0', 'UTF-8'); $dom2->appendChild($dom2->importNode($node->cloneNode(true), TRUE)); $dom2->formatOutput = true; echo __xml_norm($dom2->saveXML());
/** * Parse xmlData and return parsed result * */ private function parse(&$xmlData) { $result = array(); $doc = new DomDocument(); // Try to load XML or return parse error if (false == @$doc->loadXml($xmlData)) { // Try to fix XML by Tidy and try to load one more time if (function_exists("tidy_repair_string")) { $xmlData = tidy_repair_string($xmlData, array('output-xml' => true, 'input-xml' => true), 'utf8'); } if (false == @$doc->loadXml($xmlData)) { $this->lastError = self::$parseError; return false; } } unset($xmlData); $xpath = new DOMXPath($doc); // Register xml name spaces $this->registerNamespaces($xpath); // Parse channel tags foreach ($this->channelTags as &$tag) { $result[$tag] = $xpath->evaluate("string(channel/{$tag})"); if ($tag == 'lastBuildDate') { $this->formatDate($result[$tag]); } } // Parse items // @todo: Zjistit, co bude rychlejsi //$items = $doc->getElementsByTagName('item'); $items = $xpath->evaluate('/rss/channel/item'); foreach ($items as $item) { $tmpItem = array(); // Parse item tags foreach ($this->itemTags as &$tag) { switch ($tag) { case 'pubDate': $tmpItem[$tag] = $xpath->evaluate('string(pubDate)', $item); $this->formatDate($tmpItem[$tag]); break; case 'category': // Category is multivalue tag $tmpItem[$tag] = array(); foreach ($xpath->query('category', $item) as $node) { $tmpItem[$tag][] = trim($node->nodeValue); } break; case 'title': case 'description': $tmpItem[$tag] = $xpath->evaluate("string({$tag})", $item); if ($this->stripHtml) { $tmpItem[$tag] = strip_tags($tmpItem[$tag]); $tmpItem[$tag] = html_entity_decode($tmpItem[$tag], ENT_QUOTES, 'UTF-8'); } $tmpItem[$tag] = trim($tmpItem[$tag]); break; default: $tmpItem[$tag] = trim($xpath->evaluate("string({$tag})", $item)); break; } } $result['items'][] = $tmpItem; // If limit number of items is reached, stop processing remaining items if (count($result['items']) == $this->itemsLimit) { break; } } // Calc items count $result['itemsCount'] = isset($result['items']) ? count($result['items']) : 0; return $result; }
/** * Loads data form XML file, and merges it with main oDomXML. * * @param string $sMenuFile which file to load * @param DomDocument $oDom where to load */ protected function _loadFromFile($sMenuFile, $oDom) { $blMerge = false; $oDomFile = new DomDocument(); $oDomFile->preserveWhiteSpace = false; if (!@$oDomFile->load($sMenuFile)) { $blMerge = true; } elseif (is_readable($sMenuFile) && ($sXml = @file_get_contents($sMenuFile))) { // looking for non supported character encoding if (getStr()->preg_match("/encoding\\=(.*)\\?\\>/", $sXml, $aMatches) !== 0) { if (isset($aMatches[1])) { $sCurrEncoding = trim($aMatches[1], "\""); if (!in_array(strtolower($sCurrEncoding), $this->_aSupportedExpathXmlEncodings)) { $sXml = str_replace($aMatches[1], "\"UTF-8\"", $sXml); $sXml = iconv($sCurrEncoding, "UTF-8", $sXml); } } } // load XML as string if (@$oDomFile->loadXml($sXml)) { $blMerge = true; } } if ($blMerge) { $this->_merge($oDomFile, $oDom); } }
/** * Massage the SVG image data for converters which don't understand some path data syntax. * * This is necessary for rsvg and ImageMagick when compiled with rsvg support. * Upstream bug is https://bugzilla.gnome.org/show_bug.cgi?id=620923, fixed 2014-11-10, so * this will be needed for a while. (T76852) * * @param string $svg SVG image data * @return string Massaged SVG image data */ protected function massageSvgPathdata($svg) { $dom = new DomDocument(); $dom->loadXml($svg); foreach ($dom->getElementsByTagName('path') as $node) { $pathData = $node->getAttribute('d'); // Make sure there is at least one space between numbers, and that leading zero is not omitted. // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483". $pathData = preg_replace('/(-?)(\\d*\\.\\d+|\\d+)/', ' ${1}0$2 ', $pathData); // Strip unnecessary leading zeroes for prettiness, not strictly necessary $pathData = preg_replace('/([ -])0(\\d)/', '$1$2', $pathData); $node->setAttribute('d', $pathData); } return $dom->saveXml(); }
/** * Performs a Plesk API request, returns raw API response text * * @param string packet * @return string * @throws ApiRequestException */ private function sendRequest($packet) { $domdoc = new \DomDocument('1.0', 'UTF-8'); if ($domdoc->loadXml($packet) === FALSE) { $this->error = 'Failed to load payload'; return FALSE; } curl_setopt($this->curl, CURLOPT_POSTFIELDS, $domdoc->saveHTML()); $result = curl_exec($this->curl); if (curl_errno($this->curl)) { $errmsg = curl_error($this->curl); $errcode = curl_errno($this->curl); curl_close($this->curl); throw new ApiRequestException($errmsg, $errcode); } $info = curl_getinfo($this->curl); $this->request_header = curl_getinfo($this->curl, CURLINFO_HEADER_OUT); curl_close($this->curl); return $result; }
global $is_verbose; if ($is_verbose) { echo $str; } } $passes = 0; $failures = 0; $runs = 0; foreach (find_files(getcwd(), '/\\.test\\.php$/') as $filename) { chdir(dirname($filename)); $path = realpath(dirname(__FILE__) . '/../lib') . PATH_SEPARATOR . ini_get("include_path"); $xml = shell_exec('php -d include_path=' . escapeshellarg($path) . ' ' . escapeshellarg(basename($filename)) . ' -x'); verbose("-------------------------------------------\n"); verbose("Running suite: " . $filename . "\n"); $doc = new DomDocument(); if (@$doc->loadXml($xml)) { $q = new DomXpath($doc); $passes += $q->query('//pass')->length; $failures += $q->query('//fail')->length; foreach ($q->query('//fail') as $fail) { verbose($fail->nodeValue . "\n"); } verbose($q->query('//pass')->length . " passes, "); verbose($q->query('//fail')->length . " failures" . "\n"); } else { $failures += 1; verbose($xml); } $runs++; } verbose("===========================================\n");
<?php function loopElements($nodes) { $count = 0; foreach ($nodes as $node) { if ($node instanceof DOMElement) { $count++; if ($node->childNodes->length > 0) { $count += loopElements($node->childNodes); } } } return $count; } $xml = <<<DOC <?xml version="1.0" encoding="UTF-8"?> <root xmlns:xi="http://www.w3.org/2001/XInclude"> <a> <a_child1>ac1</a_child1> <a_child2>ac2</a_child2> </a> <b><xi:include xpointer="xpointer(/root/a)" /></b> <c><xi:include xpointer="xpointer(/root/b)" /></c> </root> DOC; $doc = new DomDocument(); $doc->loadXml($xml); $doc->xinclude(); $count = loopElements(array($doc->documentElement)); var_dump($count);