PHP DOMDocument Code Examples

This page contains top rated real world PHP examples of DOMDocument extracted from open source projects. You can rate examples to help us improve the quality of examples
Example #1
Show file File: eztocoperator.php Project: nottavi/ezpublish
0
    function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters, $placement )
    {
        $dom = $namedParameters['dom'];
        if ( $dom instanceof eZContentObjectAttribute )
        {
            $this->ObjectAttributeId = $dom->attribute( 'id' );
            $content = $dom->attribute( 'content' );
            $xmlData = $content->attribute( 'xml_data' );

            $domTree = new DOMDocument( '1.0', 'utf-8' );
            $domTree->preserveWhiteSpace = false;
            $success = $domTree->loadXML( $xmlData );

            $tocText = '';
            if ( $success )
            {
                $this->HeaderCounter = array();
                $this->LastHeaderLevel = 0;

                $rootNode = $domTree->documentElement;
                $tocText .= $this->handleSection( $rootNode );

                while ( $this->LastHeaderLevel > 0 )
                {
                    $tocText .= "</li>\n</ul>\n";
                    $this->LastHeaderLevel--;
                }
            }
        }
        $operatorValue = $tocText;
    }
Example #2
Show file File: Categories.php Project: BGCX067/faett-channel-svn-to-git
0
 /**
  * (non-PHPdoc)
  * @see lib/Faett/Channel/Serializer/Interfaces/Faett_Channel_Serializer_Interfaces_Serializer#serialize()
  */
 public function serialize()
 {
     try {
         // initialize a new DOM document
         $doc = new DOMDocument('1.0', 'UTF-8');
         // create new namespaced root element
         $a = $doc->createElementNS($this->_namespace, 'a');
         // add the schema to the root element
         $a->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi:schemaLocation', 'http://pear.php.net/dtd/rest.allcategories http://pear.php.net/dtd/rest.allcategories.xsd');
         // create an element for the channel's name
         $ch = $doc->createElement('ch');
         $ch->nodeValue = Mage::helper('channel')->getChannelName();
         // append the element with the channel's name to the root element
         $a->appendChild($ch);
         // load the product's attributes
         $attributes = $this->_category->getSelectOptions();
         // iterate over the channel's categories
         foreach ($attributes as $attribute) {
             $c = $doc->createElement('c');
             $c->setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '/channel/index/c/' . $attribute . '/info.xml');
             $c->nodeValue = $attribute;
             // append the XLink to the root element
             $a->appendChild($c);
         }
         // append the root element to the DOM tree
         $doc->appendChild($a);
         // return the XML document
         return $doc->saveXML();
     } catch (Exception $e) {
         return $e->getMessage();
     }
 }
Example #3
Show file File: ConverterTest.php Project: pradeep-wagento/magento2
0
 /**
  * Testing converting not valid cron configuration, expect to get exception
  *
  * @expectedException \InvalidArgumentException
  */
 public function testConvertWrongConfiguration()
 {
     $xmlFile = __DIR__ . '/_files/sales_invalid.xml';
     $dom = new \DOMDocument();
     $dom->loadXML(file_get_contents($xmlFile));
     $this->_converter->convert($dom);
 }
Example #4
Show file File: recipe.php Project: Broutard/MagicMirror
0
function loadDOC($html)
{
    $doc = new DOMDocument('1.0', 'UTF8');
    $doc->formatOutput = false;
    @$doc->loadHTML($html, LIBXML_COMPACT | LIBXML_NOERROR | LIBXML_NOBLANKS | LIBXML_NOWARNING | LIBXML_ERR_NONE | LIBXML_NOXMLDECL | LIBXML_HTML_NODEFDTD | LIBXML_PARSEHUGE);
    return $doc;
}
Example #5
Show file File: JobTrainingActive.php Project: fredcido/simuweb
0
 /**
  *
  * @return string
  */
 public function getMessage()
 {
     if (empty($this->_jobTraining)) {
         return '';
     }
     $this->_dom = new DOMDocument();
     $classMessage = 'alert ';
     $divFluid = $this->_dom->createElement('div');
     $divMessage = $this->_dom->createElement('div');
     $divFluid->setAttribute('class', 'row-fluid');
     if ($this->_jobTraining->status != 1) {
         $classMessage .= 'alert-error';
         $iconClass = 'icon-remove-sign';
         $alertText = ' Atensaun ';
         $message = ' Job Training ' . ($this->_jobTraining->status == 2 ? 'Kansela' : 'Taka') . ' tiha ona, La bele halo Atualizasaun.';
     } else {
         $iconClass = 'icon-ok-sign';
         $classMessage .= 'alert-success';
         $alertText = '';
         $message = ' Job Training Loke, então bele halo Atualizasaun.';
     }
     $divMessage->setAttribute('class', $classMessage);
     $strong = $this->_dom->createElement('strong');
     $i = $this->_dom->createElement('i');
     $i->setAttribute('class', $iconClass);
     $strong->appendChild($i);
     $strong->appendChild($this->_dom->createTextNode($alertText));
     $divMessage->appendChild($strong);
     $divMessage->appendChild($this->_dom->createTextNode($message));
     $divFluid->appendChild($divMessage);
     $this->_dom->appendChild($divFluid);
     return $this->_dom->saveHTML();
 }
Example #6
Show file File: Settings.php Project: kokkez/shineisp
0
 /**
 * Save the setup data
 * @param array $dbconfig
 * @param array $preferences
 * 
 * <?xml version="1.0" encoding="UTF-8"?>
 		<shineisp>
 			<config>
 				<database>
 					<hostname>localhost</hostname>
 					<db>shineisp</db>
 					<username>shineisp</username>
 					<password>shineisp2013</password>
 				</database>
 			</config>
 		</shineisp>
 */
 public static function saveConfig($dbconfig, $version = null)
 {
     try {
         $xml = new SimpleXMLElement('<shineisp></shineisp>');
         if (!empty($version)) {
             $xml->addAttribute('version', $version);
         }
         $xml->addAttribute('setupdate', date('Ymdhis'));
         $config = $xml->addChild('config');
         // Database Configuration
         $database = $config->addChild('database');
         $database->addChild('hostname', $dbconfig->hostname);
         $database->addChild('username', $dbconfig->username);
         $database->addChild('password', $dbconfig->password);
         $database->addChild('database', $dbconfig->database);
         // Get the xml string
         $xmlstring = $xml->asXML();
         // Prettify and save the xml configuration
         $dom = new DOMDocument();
         $dom->loadXML($xmlstring);
         $dom->formatOutput = true;
         $dom->saveXML();
         // Save the config xml file
         if (@$dom->save(APPLICATION_PATH . "/configs/config.xml")) {
             Shineisp_Commons_Utilities::log("Update ShineISP config xml file");
             return true;
         } else {
             throw new Exception("Error on saving the xml file in " . APPLICATION_PATH . "/configs/config.xml <br/>Please check the folder permissions");
         }
     } catch (Exception $e) {
         throw new Exception($e->getMessage());
     }
     return false;
 }
Example #7
Show file File: AkTestApplication.php Project: joeymetal/v1
0
 function _testXPath($xpath_expression)
 {
     if (!class_exists('DOMDocument') || !class_exists('DOMXPath')) {
         if (function_exists('domxml_open_mem')) {
             $dom = domxml_open_mem($this->_response);
             if (!$dom) {
                 $this->fail('Error parsing doc');
                 return false;
             }
             var_dump($dom);
             $xpath = $dom->xpath_init();
             var_dump($xpath);
             $ctx = $dom->xpath_new_context();
             var_dump($xpath_expression);
             $result = $ctx->xpath_eval($xpath_expression);
             var_dump($result);
             $return = new stdClass();
             $return->length = count($result->nodeset);
             return $return;
         }
         $this->fail('No xpath support built in');
         return false;
     } else {
         if (extension_loaded('domxml')) {
             $this->fail('Please disable the domxml extension. Only php5 builtin domxml is supported');
             return false;
         }
     }
     $dom = new DOMDocument();
     $dom->loadHtml($this->_response);
     $xpath = new DOMXPath($dom);
     $node = $xpath->query($xpath_expression);
     return $node;
 }
Example #8
Show file File: Nedgame.class.php Project: mrpapercut/gameshopsnl
0
 private function parseResults($html)
 {
     $dom = new DOMDocument();
     $dom->loadHTML($html);
     $xpath = new DOMXpath($dom);
     $elements = $xpath->query('//*[@id="middenkolom"]/div/table/tbody/tr');
     $results = array();
     if (!is_null($elements)) {
         foreach ($elements as $element) {
             // Get image
             foreach ($xpath->query('td[1]/a/img', $element) as $image) {
                 $imageUrl = 'http://www.nedgame.nl' . $image->getAttribute('src');
             }
             // Get link & title
             foreach ($xpath->query('td[2]/a', $element) as $link) {
                 $url = $link->getAttribute('href');
                 $title = $link->nodeValue;
             }
             // Get price
             foreach ($xpath->query('td[3]/div/div[4]', $element) as $prices) {
                 preg_match('/([0-9,\\-]+)/', $prices->nodeValue, $matches);
                 $price = $matches[0];
             }
             // Get platform
             foreach ($xpath->query('td[2]/span', $element) as $details) {
                 preg_match('/Platform: (.*)Type:/', $details->nodeValue, $matches);
                 $platform = $matches[1];
             }
             $results[] = array('title' => $title, 'url' => $url, 'img' => $imageUrl, 'platform' => $platform, 'price' => $price);
         }
         return $results;
     }
 }
Example #9
Show file File: Typo3PageContentExtractor.php Project: sitegeist/ext-solr
0
 /**
  * Exclude some html parts by class inside content wrapped with TYPO3SEARCH_begin and TYPO3SEARCH_end
  * markers.
  *
  * @param string $indexableContent HTML markup
  * @return string HTML
  */
 public function excludeContentByClass($indexableContent)
 {
     if (empty(trim($indexableContent))) {
         return html_entity_decode($indexableContent);
     }
     $excludeClasses = $this->getConfiguration()->getIndexQueuePagesExcludeContentByClassArray();
     if (count($excludeClasses) === 0) {
         return html_entity_decode($indexableContent);
     }
     $isInContent = Util::containsOneOfTheStrings($indexableContent, $excludeClasses);
     if (!$isInContent) {
         return html_entity_decode($indexableContent);
     }
     $doc = new \DOMDocument('1.0', 'UTF-8');
     libxml_use_internal_errors(true);
     $doc->loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL . $indexableContent);
     $xpath = new \DOMXPath($doc);
     foreach ($excludeClasses as $excludePart) {
         $elements = $xpath->query("//*[contains(@class,'" . $excludePart . "')]");
         if (count($elements) == 0) {
             continue;
         }
         foreach ($elements as $element) {
             $element->parentNode->removeChild($element);
         }
     }
     $html = $doc->saveHTML($doc->documentElement->parentNode);
     // remove XML-Preamble, newlines and doctype
     $html = preg_replace('/(<\\?xml[^>]+\\?>|\\r?\\n|<!DOCTYPE.+?>)/imS', '', $html);
     $html = str_replace(array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $html);
     return $html;
 }
Example #10
Show file File: program_xml.php Project: h3len/Project
0
 function show()
 {
     $channel_id = $this->input['channel_id'];
     if (!$channel_id) {
         $this->errorOutput('该频道不存在或者已被删除');
     }
     $dates = $this->input['dates'];
     if (!$dates) {
         $this->errorOutput('这一天不存在节目');
     }
     $sql = "select * from " . DB_PREFIX . "program where channel_id=" . $channel_id . " AND dates='" . $dates . "' ORDER BY start_time ASC ";
     $q = $this->db->query($sql);
     header('Content-Type: text/xml; charset=UTF-8');
     $dom = new DOMDocument('1.0', 'utf-8');
     $program = $dom->createElement('program');
     while ($row = $this->db->fetch_array($q)) {
         $item = $dom->createElement('item');
         $item->setAttribute('name', urldecode($row['theme']));
         $item->setAttribute('startTime', $row['start_time'] * 1000);
         $item->setAttribute('duration', $row['toff'] * 1000);
         $program->appendChild($item);
     }
     $dom->appendChild($program);
     echo $dom->saveXml();
 }
Example #11
Show file File: Record.php Project: bryandease/VuFind-Plus
0
 /**
  * Process parameters and display the page.
  *
  * @return void
  * @access public
  */
 public function launch()
 {
     global $interface;
     // Retrieve the record from the index
     if (!($record = $this->db->getRecord($_GET['id']))) {
         PEAR_Singleton::raiseError(new PEAR_Error('Record Does Not Exist'));
     }
     // Send basic information to the template.
     $interface->setPageTitle(isset($record['heading']) ? $record['heading'] : 'Heading unavailable.');
     $interface->assign('record', $record);
     // Load MARC data
     require_once ROOT_DIR . '/sys/MarcLoader.php';
     $marcRecord = MarcLoader::loadMarcRecordFromRecord($record);
     if (!$marcRecord) {
         PEAR_Singleton::raiseError(new PEAR_Error('Cannot Process MARC Record'));
     }
     $xml = trim($marcRecord->toXML());
     // Transform MARCXML
     $style = new DOMDocument();
     $style->load('services/Record/xsl/record-marc.xsl');
     $xsl = new XSLTProcessor();
     $xsl->importStyleSheet($style);
     $doc = new DOMDocument();
     if ($doc->loadXML($xml)) {
         $html = $xsl->transformToXML($doc);
         $interface->assign('details', $html);
     }
     // Assign the ID of the last search so the user can return to it.
     $interface->assign('lastsearch', isset($_SESSION['lastSearchURL']) ? $_SESSION['lastSearchURL'] : false);
     // Display Page
     $interface->setTemplate('record.tpl');
     $interface->display('layout.tpl');
 }
Example #12
Show file File: GetOrder.php Project: ankkal/SPN_project
0
 function invokeGetOrder(MarketplaceWebServiceOrders_Interface $service, $request)
 {
     try {
         $response = $service->GetOrder($request);
         $dom = new DOMDocument();
         $dom->loadXML($response->toXML());
         $dom->preserveWhiteSpace = false;
         $dom->formatOutput = true;
         $data = $dom->saveXML();
         $xml = simplexml_load_string($data);
         if (empty($xml->GetOrderResult->Orders)) {
             return false;
         } else {
             //$xml->GetOrderResult->Orders
             return true;
         }
     } catch (MarketplaceWebServiceOrders_Exception $ex) {
         $message = 'MWS Order API : Caught Exception : ' . $ex->getMessage() . "\n";
         $message .= "Response Status Code: " . $ex->getStatusCode() . "\n";
         $message .= "Error Code: " . $ex->getErrorCode() . "\n";
         $message .= "Error Type: " . $ex->getErrorType() . "\n";
         $param['message'] = $message;
         $this->generate_log($param);
     }
 }
Example #13
Show file File: NSIProxy.php Project: ufrgs-hyman/proxy-agg
0
 function decodeGz64()
 {
     $contentNodes = $this->xpath->query("//content");
     foreach ($contentNodes as $contentNode) {
         if ($contentNode->getAttribute("contentType") == "application/x-gzip" && $contentNode->getAttribute('contentTransferEncoding') == "base64") {
             $contentDOM = new \DOMDocument();
             $contentDOM->loadXML(gzdecode(base64_decode($contentNode->nodeValue)));
             $xmlns = "http://schemas.ogf.org/nml/2013/05/base#";
             $tagName = "Topology";
             foreach ($contentDOM->getElementsByTagNameNS($xmlns, $tagName) as $netNode) {
                 $node = $this->xml->importNode($netNode, true);
                 $contentNode->nodeValue = "";
                 $contentNode->removeAttribute("contentType");
                 $contentNode->removeAttribute('contentTransferEncoding');
                 $contentNode->appendChild($node);
             }
             $xmlns = "http://schemas.ogf.org/nsi/2014/02/discovery/nsa";
             $tagName = "nsa";
             foreach ($contentDOM->getElementsByTagNameNS($xmlns, $tagName) as $nsaNode) {
                 $node = $this->xml->importNode($nsaNode, true);
                 $contentNode->nodeValue = "";
                 $contentNode->removeAttribute("contentType");
                 $contentNode->removeAttribute('contentTransferEncoding');
                 $contentNode->appendChild($node);
             }
         }
     }
 }
Example #14
Show file File: seostats.google.php Project: andreassetiawanhartanto/PDKKI
0
 /**
  * Returns array, containing detailed results for any Google search.
  *
  * @access       private
  * @param        string        $query      String, containing the search query.
  * @param        string        $tld        String, containing the desired Google top level domain.
  * @return       array                     Returns array, containing the keys 'URL', 'Title' and 'Description'.
  */
 public static function googleArray($query)
 {
     $result = array();
     $pages = 1;
     $delay = 0;
     for ($start = 0; $start < $pages; $start++) {
         $url = 'http://www.google.' . GOOGLE_TLD . '/custom?q=' . $query . '&filter=0' . '&num=100' . ($start == 0 ? '' : '&start=' . $start . '00');
         $str = SEOstats::cURL($url);
         if (preg_match("#answer=86640#i", $str)) {
             $e = 'Please read: http://www.google.com/support/websearch/' . 'bin/answer.py?&answer=86640&hl=en';
             throw new SEOstatsException($e);
         } else {
             $html = new DOMDocument();
             @$html->loadHtml($str);
             $xpath = new DOMXPath($html);
             $links = $xpath->query("//div[@class='g']//a");
             $descs = $xpath->query("//td[@class='j']//div[@class='std']");
             $i = 0;
             foreach ($links as $link) {
                 if (!preg_match('#cache#si', $link->textContent) && !preg_match('#similar#si', $link->textContent)) {
                     $result[] = array('url' => $link->getAttribute('href'), 'title' => utf8_decode($link->textContent), 'descr' => utf8_decode($descs->item($i)->textContent));
                     $i++;
                 }
             }
             if (preg_match('#<div id="nn"><\\/div>#i', $str) || preg_match('#<div id=nn><\\/div>#i', $str)) {
                 $pages += 1;
                 $delay += 200000;
                 usleep($delay);
             } else {
                 $pages -= 1;
             }
         }
     }
     return $result;
 }
Example #15
Show file File: xslt.php Project: roman-rybalko/wcs
0
 /**
  * Обрабатывает данные.
  * @param string $data XML-строка
  */
 public function process($data)
 {
     $errorHandler = new \WebConstructionSet\Xml\LibxmlErrorHandler();
     $xml = new \DOMDocument();
     if (!$xml->loadXML($data)) {
         throw new \ErrorException('Document parse failed. ' . $errorHandler->getErrorString(), null, null, __FILE__, __LINE__);
     }
     $xsl = new \DOMDocument();
     if ($this->xslString) {
         if (!$xsl->loadXML($this->xslString)) {
             throw new \ErrorException('XSL stylesheet load/parse failed. ' . $errorHandler->getErrorString(), null, null, __FILE__, __LINE__);
         }
     } else {
         $xslPath = $this->getXslStylesheetPath($xml);
         if (!$xslPath) {
             throw new \ErrorException('XSL stylesheet path is not found.', null, null, __FILE__, __LINE__);
         }
         if (!$xsl->load($xslPath)) {
             throw new \ErrorException('XSL stylesheet load/parse failed. ' . $errorHandler->getErrorString(), null, null, __FILE__, __LINE__);
         }
     }
     $xslt = new \XSLTProcessor();
     if (!$xslt->importStylesheet($xsl)) {
         throw new \ErrorException('Import XSL stylesheet failed. ' . $errorHandler->getErrorString(), null, null, __FILE__, __LINE__);
     }
     $this->resultDoc = $xslt->transformToDoc($xml);
     if (!$this->resultDoc) {
         throw new \ErrorException('XSLT transform failed. ' . $errorHandler->getErrorString(), null, null, __FILE__, __LINE__);
     }
     // no return
 }
Example #16
Show file File: XMLSchemaTest.php Project: robertowest/CuteFlow-V4
0
 /**
  * @dataProvider dataValidateSchemaFiles
  * @param string $file
  */
 public function testValidateSchema($file)
 {
     $found = false;
     $dom = new \DOMDocument('1.0', 'UTF-8');
     $dom->load($file);
     $dbalElements = $dom->getElementsByTagNameNS("http://symfony.com/schema/dic/doctrine", "config");
     if ($dbalElements->length) {
         $dbalDom = new \DOMDocument('1.0', 'UTF-8');
         $dbalNode = $dbalDom->importNode($dbalElements->item(0));
         $dbalDom->appendChild($dbalNode);
         $ret = $dbalDom->schemaValidate(__DIR__ . "/../../Resources/config/schema/doctrine-1.0.xsd");
         $this->assertTrue($ret, "DoctrineBundle Dependency Injection XMLSchema did not validate this XML instance.");
         $found = true;
     }
     $ormElements = $dom->getElementsByTagNameNS("http://symfony.com/schema/dic/doctrine", "config");
     if ($ormElements->length) {
         $ormDom = new \DOMDocument('1.0', 'UTF-8');
         $ormNode = $ormDom->importNode($ormElements->item(0));
         $ormDom->appendChild($ormNode);
         $ret = $ormDom->schemaValidate(__DIR__ . "/../../Resources/config/schema/doctrine-1.0.xsd");
         $this->assertTrue($ret, "DoctrineBundle Dependency Injection XMLSchema did not validate this XML instance.");
         $found = true;
     }
     $this->assertTrue($found, "Neither <doctrine:orm> nor <doctrine:dbal> elements found in given XML. Are namespaces configured correctly?");
 }
Example #17
Show file File: DeployDirReader.php Project: sleepyycat/WebFramework
0
function parseResinImprFile($file_path)
{
    global $hostDict;
    $doc = new DOMDocument();
    @$doc->loadHTMLFile($file_path);
    $query = "//table[1]/tr[@class != 'first']/td[position() < 3]";
    $xpath = new DOMXPath($doc);
    $entries = $xpath->query($query);
    $index = 0;
    $key = "";
    $value = "";
    foreach ($entries as $entry) {
        if ($index % 2 == 0) {
            $key = $entry->nodeValue;
        } else {
            $value = $entry->nodeValue;
        }
        if ($index != 0 and $index % 2 == 1) {
            if ($key == "AD_EXCHANGE.bidResult") {
                # 还不能区分bid 和 bidResult, 所以加到一起
                $key = "AD_EXCHANGE.bid";
            }
            if (array_key_exists($key, $hostDict) && !in_array($value, $hostDict[$key])) {
                array_push($hostDict[$key], $value);
            }
        }
        $index++;
    }
}
Example #18
Show file File: ConverterTest.php Project: pradeep-wagento/magento2
0
 public function testConvert()
 {
     $inputData = new \DOMDocument();
     $inputData->load(__DIR__ . '/_files/webapi.xml');
     $expectedResult = (require __DIR__ . '/_files/webapi.php');
     $this->assertEquals($expectedResult, $this->_model->convert($inputData));
 }
Example #19
Show file File: ArcanistPhpcsLinter.php Project: barcelonascience/arcanist
0
 protected function parseLinterOutput($path, $err, $stdout, $stderr)
 {
     // NOTE: Some version of PHPCS after 1.4.6 stopped printing a valid, empty
     // XML document to stdout in the case of no errors. If PHPCS exits with
     // error 0, just ignore output.
     if (!$err) {
         return array();
     }
     $report_dom = new DOMDocument();
     $ok = @$report_dom->loadXML($stdout);
     if (!$ok) {
         return false;
     }
     $files = $report_dom->getElementsByTagName('file');
     $messages = array();
     foreach ($files as $file) {
         foreach ($file->childNodes as $child) {
             if (!$child instanceof DOMElement) {
                 continue;
             }
             if ($child->tagName == 'error') {
                 $prefix = 'E';
             } else {
                 $prefix = 'W';
             }
             $source = $child->getAttribute('source');
             $code = 'PHPCS.' . $prefix . '.' . $source;
             $message = id(new ArcanistLintMessage())->setPath($path)->setName($source)->setLine($child->getAttribute('line'))->setChar($child->getAttribute('column'))->setCode($code)->setDescription($child->nodeValue)->setSeverity($this->getLintMessageSeverity($code));
             $messages[] = $message;
         }
     }
     return $messages;
 }
Example #20
Show file File: NativeTest.php Project: kandy/system
0
 /**
  * @todo Implement testSerialize().
  */
 public function testSerialize()
 {
     $dom = new DOMDocument();
     $dom->appendChild($dom->createElement('xml'));
     $this->object->serialize('test', $dom->documentElement);
     self::assertXmlStringEqualsXmlString('<xml>test</xml>', $dom->saveXml());
 }
Example #21
Show file File: CiteProc.php Project: apmon/WikiPapers2
0
 function init($csl, $lang)
 {
     // define field values appropriate to your data in the csl_mapper class and un-comment the next line.
     $this->mapper = new csl_mapper();
     $this->quash = array();
     $csl_doc = new DOMDocument();
     if ($csl_doc->loadXML($csl)) {
         $style_nodes = $csl_doc->getElementsByTagName('style');
         if ($style_nodes) {
             foreach ($style_nodes as $style) {
                 $this->style = new csl_style($style);
             }
         }
         $info_nodes = $csl_doc->getElementsByTagName('info');
         if ($info_nodes) {
             foreach ($info_nodes as $info) {
                 $this->info = new csl_info($info);
             }
         }
         $this->locale = new csl_locale($lang);
         $this->locale->set_style_locale($csl_doc);
         $macro_nodes = $csl_doc->getElementsByTagName('macro');
         if ($macro_nodes) {
             $this->macros = new csl_macros($macro_nodes, $this);
         }
         $citation_nodes = $csl_doc->getElementsByTagName('citation');
         foreach ($citation_nodes as $citation) {
             $this->citation = new csl_citation($citation, $this);
         }
         $bibliography_nodes = $csl_doc->getElementsByTagName('bibliography');
         foreach ($bibliography_nodes as $bibliography) {
             $this->bibliography = new csl_bibliography($bibliography, $this);
         }
     }
 }
Example #22
Show file File: WebServiceClientProxy.php Project: pelif/studyWS
0
 public function __call($method, $arguments)
 {
     $dom = new DOMDocument('1.0', 'UTF-8');
     $element = $dom->createElement('method');
     $element->setAttribute('name', $method);
     foreach ($arguments as $argument) {
         $child = $dom->createElement('argument');
         $textNode = $dom->createTextNode($argument);
         $child->appendChild($textNode);
         $element->appendChild($child);
     }
     $dom->appendChild($element);
     $data = 'service=' . $dom->saveXML();
     $params = array('http' => array('method' => 'POST', 'content' => $data));
     $ctx = stream_context_create($params);
     $fp = @fopen($this->server, 'rb', false, $ctx);
     if (!$fp) {
         throw new Exception('Problem with URL');
     }
     $response = @stream_get_contents($fp);
     if ($response === false) {
         throw new Exception("Problem reading data from {$this->server}");
     }
     $dom = new DOMDocument(null, 'UTF-8');
     $dom->loadXML($response);
     $result = $dom->childNodes->item(0)->childNodes->item(0)->nodeValue;
     $type = $dom->childNodes->item(0)->childNodes->item(1)->nodeValue;
     settype($result, $type);
     return $result;
 }
Example #23
Show file File: XmlMappingDriverTest.php Project: dracony/forked-php-orm-benchmark
0
 /**
  * @param string $xmlMappingFile
  * @dataProvider dataValidSchema
  */
 public function testValidateXmlSchema($xmlMappingFile)
 {
     $xsdSchemaFile = __DIR__ . "/../../../../../doctrine-mapping.xsd";
     $dom = new \DOMDocument('UTF-8');
     $dom->load($xmlMappingFile);
     $this->assertTrue($dom->schemaValidate($xsdSchemaFile));
 }
Example #24
Show file File: OnlineArticle.php Project: master3395/CBPPlatform
0
 public function __construct($url)
 {
     if (!preg_match('!^https?://!i', $url)) {
         $url = 'http://' . $url;
     }
     $data = Http::Request($url);
     //$enc = mb_detect_encoding($str, "UTF-8,ISO-8859-1,ASCII");
     $html = mb_convert_encoding($data, "UTF-8", "UTF-8,ISO-8859-1,ASCII");
     //$html = utf8_encode($html);
     $r = new Readability($html, $url);
     $r->init();
     if (!isset($this->metadata["title"])) {
         $this->metadata["title"] = CharacterEntities::convert(strip_tags($r->getTitle()->innerHTML));
     }
     if (!isset($this->metadata["author"])) {
         $parts = parse_url($url);
         $this->metadata["author"] = $parts["host"];
     }
     $article = $r->getContent()->innerHTML;
     if (substr($article, 0, 5) == "<body") {
         $article = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head>" . $article . "</html>";
     } else {
         $article = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head><body>" . $article . "</body></html>";
     }
     $doc = new DOMDocument();
     @$doc->loadHTML($article) or die($article);
     $doc->normalizeDocument();
     $this->images = $this->handleImages($doc, $url);
     $this->text = $doc->saveHTML();
 }
Example #25
Show file File: DOMLex.php Project: atikahmed/joomla-probid
0
 public function tokenizeHTML($html, $config, &$context)
 {
     $html = $this->normalize($html, $config, $context);
     // attempt to armor stray angled brackets that cannot possibly
     // form tags and thus are probably being used as emoticons
     if ($config->get('Core', 'AggressivelyFixLt')) {
         $char = '[^a-z!\\/]';
         $comment = "/<!--(.*?)(-->|\\z)/is";
         $html = preg_replace_callback($comment, array('HTMLPurifier_Lexer_DOMLex', 'callbackArmorCommentEntities'), $html);
         $html = preg_replace("/<({$char})/i", '&lt;\\1', $html);
         $html = preg_replace_callback($comment, array('HTMLPurifier_Lexer_DOMLex', 'callbackUndoCommentSubst'), $html);
         // fix comments
     }
     // preprocess html, essential for UTF-8
     $html = $this->wrapHTML($html, $config, $context);
     $doc = new DOMDocument();
     $doc->encoding = 'UTF-8';
     // theoretically, the above has this covered
     set_error_handler(array($this, 'muteErrorHandler'));
     $doc->loadHTML($html);
     restore_error_handler();
     $tokens = array();
     $this->tokenizeDOM($doc->getElementsByTagName('html')->item(0)->getElementsByTagName('body')->item(0)->getElementsByTagName('div')->item(0), $tokens);
     return $tokens;
 }
Example #26
Show file File: Converter.php Project: tingyeeh/magento2
0
 /**
  * Convert dom node tree to array
  *
  * @param \DOMDocument $source
  * @return array
  * @throws \InvalidArgumentException
  */
 public function convert($source)
 {
     $output = [];
     /** @var \DOMNodeList $events */
     $events = $source->getElementsByTagName('event');
     /** @var \DOMNode $eventConfig */
     foreach ($events as $eventConfig) {
         $eventName = $eventConfig->attributes->getNamedItem('name')->nodeValue;
         $eventObservers = [];
         /** @var \DOMNode $observerConfig */
         foreach ($eventConfig->childNodes as $observerConfig) {
             if ($observerConfig->nodeName != 'observer' || $observerConfig->nodeType != XML_ELEMENT_NODE) {
                 continue;
             }
             $observerNameNode = $observerConfig->attributes->getNamedItem('name');
             if (!$observerNameNode) {
                 throw new \InvalidArgumentException('Attribute name is missed');
             }
             $config = $this->_convertObserverConfig($observerConfig);
             $config['name'] = $observerNameNode->nodeValue;
             $eventObservers[$observerNameNode->nodeValue] = $config;
         }
         $output[$eventName] = $eventObservers;
     }
     return $output;
 }
Example #27
Show file File: post-option.php Project: hongviet119/dlvv
0
function add_post_option_element()
{
    global $post, $post_meta_boxes;
    // init array
    $post_meta_boxes['Choose Left Sidebar']['options'] = get_sidebar_name();
    $post_meta_boxes['Choose Right Sidebar']['options'] = $post_meta_boxes['Choose Left Sidebar']['options'];
    echo '<div id="gdl-overlay-wrapper">';
    ?>
 <div class="post-option-meta" id="post-option-meta"> <?php 
    set_nonce();
    foreach ($post_meta_boxes as $meta_box) {
        if ($meta_box['type'] == 'imagepicker') {
            $xml_string = get_post_meta($post->ID, $meta_box['xml'], true);
            if (!empty($xml_string)) {
                $xml_val = new DOMDocument();
                $xml_val->loadXML($xml_string);
                $meta_box['value'] = $xml_val->documentElement;
            }
        } else {
            if ($meta_box['type'] == 'open' || $meta_box['type'] == 'close') {
            } else {
                $meta_box['value'] = get_post_meta($post->ID, $meta_box['name'], true);
            }
        }
        print_meta($meta_box);
        if ($meta_box['type'] != 'open' && $meta_box['type'] != 'close') {
            echo "<div class='clear'></div>";
            echo empty($meta_box['hr']) ? '<hr class="separator mt20">' : '';
        }
    }
    ?>
 </div> <?php 
    echo '</div>';
}
Example #28
Show file File: init.php Project: cs-team/tiny_tiny_rss-openshift-quickstart
0
 function hook_article_filter($article)
 {
     $owner_uid = $article["owner_uid"];
     if (strpos($article["guid"], "dilbert.com") !== FALSE) {
         if (strpos($article["plugin_data"], "dilbert,{$owner_uid}:") === FALSE) {
             $doc = new DOMDocument();
             @$doc->loadHTML(fetch_file_contents($article["link"]));
             $basenode = false;
             if ($doc) {
                 $xpath = new DOMXPath($doc);
                 $entries = $xpath->query('(//img[@src])');
                 // we might also check for img[@class='strip'] I guess...
                 $matches = array();
                 foreach ($entries as $entry) {
                     if (preg_match("/dyn\\/str_strip\\/.*zoom\\.gif\$/", $entry->getAttribute("src"), $matches)) {
                         $entry->setAttribute("src", rewrite_relative_url("http://dilbert.com/", $matches[0]));
                         $basenode = $entry;
                         break;
                     }
                 }
                 if ($basenode) {
                     $article["content"] = $doc->saveXML($basenode);
                     $article["plugin_data"] = "dilbert,{$owner_uid}:" . $article["plugin_data"];
                 }
             }
         } else {
             if (isset($article["stored"]["content"])) {
                 $article["content"] = $article["stored"]["content"];
             }
         }
     }
     return $article;
 }
Example #29
Show file File: embedresources.lib.php Project: bakkertjebrood/appdeck
0
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;
}
Example #30
Show file File: Xml.php Project: apoorvkumar/bias
0
 public static function load($file)
 {
     $document = new DOMDocument();
     $document->load($file);
     $document->xinclude();
     return $document->saveXML();
 }
Frequently Used Methods