当前位置: 首页>>代码示例>>PHP>>正文


PHP DOMDocument::loadXml方法代码示例

本文整理汇总了PHP中DOMDocument::loadXml方法的典型用法代码示例。如果您正苦于以下问题:PHP DOMDocument::loadXml方法的具体用法?PHP DOMDocument::loadXml怎么用?PHP DOMDocument::loadXml使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DOMDocument的用法示例。


在下文中一共展示了DOMDocument::loadXml方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: __construct

 /**
  * Instancia uma nova validacao das Assinaturas Digitais de documentos XML
  *
  * @param string $sFile Arquivo a ser validado
  * @throws Exception
  */
 public function __construct($sFile)
 {
     if (empty($sFile)) {
         throw new Exception("Arquivo deve ser informado");
     }
     $this->sFile = $sFile;
     $this->oDomDocument = new DOMDocument();
     $this->oDomDocument->loadXml($sFile);
 }
开发者ID:arendasistemasintegrados,项目名称:mateusleme,代码行数:15,代码来源:AssinaturaDigital.php

示例2: openxml

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;
}
开发者ID:bakkertjebrood,项目名称:appdeck,代码行数:32,代码来源:embedresources.lib.php

示例3: fetchCollectionItem

/**
 * Load a single item by itemKey only if it belongs to a specific collection
 *
 * @param Zotero_Library $library
 * @param string $itemKey
 * @param string $collectionKey
 * @return Zotero_Item
 */
function fetchCollectionItem($library, $itemKey, $collectionKey)
{
    $citemKey = $itemKey . ',';
    //hackish way to get a single item by itemKey + collectionKey by forcing itemKey into querystring
    $aparams = array('target' => 'items', 'content' => 'json', 'itemKey' => $itemKey, 'collectionKey' => $collectionKey);
    $reqUrl = $library->apiRequestUrl($aparams) . $library->apiQueryString($aparams);
    $response = $library->_request($reqUrl, 'GET');
    if ($response->isError()) {
        return false;
        throw new Exception("Error fetching items");
    }
    $body = $response->getRawBody();
    $doc = new DOMDocument();
    $doc->loadXml($body);
    $entries = $doc->getElementsByTagName("entry");
    if (!$entries->length) {
        return false;
        throw new Exception("no item with specified key found");
    } else {
        $entry = $entries->item(0);
        $item = new Zotero_Item($entry);
        $library->items->addItem($item);
        return $item;
    }
}
开发者ID:tnajdek,项目名称:libZotero,代码行数:33,代码来源:download.php

示例4: testVisitWithoutEmbeddedVersion

 /**
  * @return \DOMDocument
  */
 public function testVisitWithoutEmbeddedVersion()
 {
     $visitor = $this->getVisitor();
     $generator = $this->getGenerator();
     $generator->startDocument(null);
     $restUser = $this->getBasicRestUser();
     $this->getVisitorMock()->expects($this->once())->method('visitValueObject');
     $locationPath = implode('/', $restUser->mainLocation->path);
     $this->addRouteExpectation('ezpublish_rest_loadUser', array('userId' => $restUser->contentInfo->id), "/user/users/{$restUser->contentInfo->id}");
     $this->addRouteExpectation('ezpublish_rest_loadContentType', array('contentTypeId' => $restUser->contentInfo->contentTypeId), "/content/types/{$restUser->contentInfo->contentTypeId}");
     $this->addRouteExpectation('ezpublish_rest_loadContentVersions', array('contentId' => $restUser->contentInfo->id), "/content/objects/{$restUser->contentInfo->id}/versions");
     $this->addRouteExpectation('ezpublish_rest_loadSection', array('sectionId' => $restUser->contentInfo->sectionId), "/content/sections/{$restUser->contentInfo->sectionId}");
     $this->addRouteExpectation('ezpublish_rest_loadLocation', array('locationPath' => $locationPath), "/content/locations/{$locationPath}");
     $this->addRouteExpectation('ezpublish_rest_loadLocationsForContent', array('contentId' => $restUser->contentInfo->id), "/content/objects/{$restUser->contentInfo->id}/locations");
     $this->addRouteExpectation('ezpublish_rest_loadUserGroupsOfUser', array('userId' => $restUser->contentInfo->id), "/user/users/{$restUser->contentInfo->id}/groups");
     $this->addRouteExpectation('ezpublish_rest_loadUser', array('userId' => $restUser->contentInfo->ownerId), "/user/users/{$restUser->contentInfo->ownerId}");
     $this->addRouteExpectation('ezpublish_rest_loadUserGroupsOfUser', array('userId' => $restUser->contentInfo->id), "/user/users/{$restUser->contentInfo->id}/groups");
     $this->addRouteExpectation('ezpublish_rest_loadRoleAssignmentsForUser', array('userId' => $restUser->contentInfo->id), "/user/users/{$restUser->contentInfo->id}/roles");
     $visitor->visit($this->getVisitorMock(), $generator, $restUser);
     $result = $generator->endDocument(null);
     $this->assertNotNull($result);
     $dom = new \DOMDocument();
     $dom->loadXml($result);
     return $dom;
 }
开发者ID:ezsystems,项目名称:ezpublish-kernel,代码行数:28,代码来源:RestUserTest.php

示例5: indexAction

 public function indexAction()
 {
     SxCms_Acl::requireAcl('ad', 'ad.edit');
     $filename = APPLICATION_PATH . '/var/ads.xml';
     $dom = new DOMDocument();
     $dom->preserveWhiteSpace = false;
     $dom->loadXml(file_get_contents($filename));
     $dom->formatOutput = true;
     $xpath = new DOMXpath($dom);
     $xml = simplexml_import_dom($dom);
     if ($this->getRequest()->isPost()) {
         $ads = $this->_getParam('ad');
         foreach ($ads as $key => $value) {
             $nodeList = $xpath->query("//zone[id='{$key}']/content");
             if ($nodeList->length) {
                 $cdata = $dom->createCDATASection(stripslashes($value));
                 $content = $dom->createElement('content');
                 $content->appendChild($cdata);
                 $nodeList->item(0)->parentNode->replaceChild($content, $nodeList->item(0));
             }
         }
         $dom->save($filename);
         $flashMessenger = $this->_helper->getHelper('FlashMessenger');
         $flashMessenger->addMessage('Advertentie werd succesvol aangepast');
     }
     $this->view->ads = $xml;
 }
开发者ID:sonvq,项目名称:2015_freelance6,代码行数:27,代码来源:AdController.php

示例6: DOMDocument

 /**
  * @see Filter::process()
  * @param $document DOMDocument|string
  * @return array Array of imported documents
  */
 function &process(&$document)
 {
     // If necessary, convert $document to a DOMDocument.
     if (is_string($document)) {
         $xmlString = $document;
         $document = new DOMDocument();
         $document->loadXml($xmlString);
     }
     assert(is_a($document, 'DOMDocument'));
     $deployment = $this->getDeployment();
     $submissions = array();
     if ($document->documentElement->tagName == $this->getPluralElementName()) {
         // Multiple element (plural) import
         for ($n = $document->documentElement->firstChild; $n !== null; $n = $n->nextSibling) {
             if (!is_a($n, 'DOMElement')) {
                 continue;
             }
             $submissions[] = $this->handleElement($n);
         }
     } else {
         assert($document->documentElement->tagName == $this->getSingularElementName());
         // Single element (singular) import
         $submissions[] = $this->handleElement($document->documentElement);
     }
     return $submissions;
 }
开发者ID:PublishingWithoutWalls,项目名称:pkp-lib,代码行数:31,代码来源:NativeImportFilter.inc.php

示例7: getSRank

 public function getSRank($domain)
 {
     $xml = '<?xml version="1.0" encoding="UTF-8"?><methodCall><methodName>getRank</methodName><params><param><value><string>0</string></value></param><param><value><string>' . htmlspecialchars($domain) . '</string></value></param><param><value><i4>0</i4></value></param></params></methodCall>';
     $request = "POST /RPC2 HTTP/1.1\r\n";
     $request .= "Host: srank.seznam.cz\r\n";
     $request .= "Content-Type: text/xml\r\n";
     $request .= "Content-Length: " . strlen($xml) . "\r\n";
     $request .= "Connection: Close\r\n\r\n";
     $request .= $xml;
     $errNo = $errStr = '';
     $socket = fsockopen('srank.seznam.cz', 80, $errNo, $errStr, 10);
     if ($socket === FALSE) {
         return -1;
     }
     fwrite($socket, $request);
     $response = '';
     while (!feof($socket)) {
         $response .= fgets($socket, 1024);
     }
     $response = preg_replace('/^(.+\\r\\n)+\\r\\n/', '', $response);
     $doc = new DOMDocument();
     if (!$doc->loadXml($response)) {
         return -1;
     }
     $xpath = new DOMXPath($doc);
     $result = $xpath->evaluate('string(//member[name = "rank"]/value)');
     if (!is_numeric($result)) {
         return -1;
     }
     $rank = round((int) $result * 100 / 255 / 10);
     return $rank;
 }
开发者ID:noblexity,项目名称:RankFace,代码行数:32,代码来源:SeznamService.php

示例8: loadXML

    public function loadXML($source, $options = 0, $appendEncoding = true, $appendDTD = true)
    {
        //append xml encoding and DTD if needed
        if ($appendEncoding) {
            //convert source encoding if needed
            if (io::isUTF8($source)) {
                if (io::strtolower(APPLICATION_DEFAULT_ENCODING) != 'utf-8') {
                    $source = utf8_decode($source);
                }
            } else {
                if (io::strtolower(APPLICATION_DEFAULT_ENCODING) == 'utf-8') {
                    $source = utf8_encode($source);
                }
            }
            if ($appendDTD) {
                $options = $options ? $options | LIBXML_DTDLOAD : LIBXML_DTDLOAD;
                $doctype = !APPLICATION_IS_WINDOWS ? '<!DOCTYPE automne SYSTEM "' . PATH_PACKAGES_FS . '/files/xhtml.ent">' : '<!DOCTYPE automne [' . file_get_contents(PATH_PACKAGES_FS . '/files/xhtml.ent') . ']>';
            }
            $source = '<?xml version="1.0" encoding="' . APPLICATION_DEFAULT_ENCODING . '"?>
			' . ($appendDTD ? $doctype : '') . '
			' . $source;
        }
        set_error_handler(array('CMS_DOMDocument', 'XmlError'));
        $return = parent::loadXml($source, $options);
        restore_error_handler();
        return $return;
    }
开发者ID:davidmottet,项目名称:automne,代码行数:27,代码来源:xmldomdocument.php

示例9: load

 /**
  * Load HTML or XML.
  * 
  * @param string $string HTML or XML string or file path
  * @param bool   $isFile Indicates that in first parameter was passed to the file path
  * @param string $type Type of document
  * @param int    $options Additional parameters
  */
 public function load($string, $isFile = false, $type = 'html', $options = 0)
 {
     if (!is_string($string)) {
         throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, is_object($string) ? get_class($string) : gettype($string)));
     }
     if (!in_array(strtolower($type), ['xml', 'html'])) {
         throw new InvalidArgumentException(sprintf('Document type must be "xml" or "html", %s given', __METHOD__, is_object($type) ? get_class($type) : gettype($type)));
     }
     if (!is_integer($options)) {
         throw new InvalidArgumentException(sprintf('%s expects parameter 4 to be integer, %s given', __METHOD__, is_object($options) ? get_class($options) : gettype($options)));
     }
     $string = trim($string);
     if ($isFile) {
         $string = $this->loadFile($string);
     }
     if (substr($string, 0, 5) !== '<?xml') {
         $prolog = sprintf('<?xml version="1.0" encoding="%s"?>', $this->document->encoding);
         $string = $prolog . $string;
     }
     $this->type = strtolower($type);
     Errors::disable();
     $this->type === 'xml' ? $this->document->loadXml($string, $options) : $this->document->loadHtml($string, $options);
     Errors::restore();
     return $this;
 }
开发者ID:imangazaliev,项目名称:didom,代码行数:33,代码来源:Document.php

示例10: preparaDados

 /**
  * Prepara os dados para processar o arquivo do webservice
  *
  * @param string $sArquivo
  * @return bool
  * @throws Exception
  */
 public function preparaDados($sArquivo)
 {
     try {
         // Foi comentado o if de verificação pois estava ocorrendo um problema na emissão e retornava um arquivo em branco.
         // Somente em ambiente de desenvolvimento
         //if (APPLICATION_ENV == 'development') {
         $oDomDocument = new DOMDocument();
         $oDomDocument->loadXml($sArquivo);
         $oData = new Zend_Date();
         $this->sNomeArquivo = "/RecepcionarLote-{$oData->getTimestamp()}.xml";
         $this->sCaminhoArquivo = TEMP_PATH;
         /**
          * Verifica se o caminho do arquivo não existe recria a pasta
          */
         if (!file_exists($this->sCaminhoArquivo)) {
             mkdir($this->sCaminhoArquivo, 0777);
         }
         /**
          * Escreve os dados no arquivo
          */
         $this->sCaminhoNomeArquivo = $this->sCaminhoArquivo . $this->sNomeArquivo;
         $aArquivo = fopen($this->sCaminhoNomeArquivo, 'w');
         fputs($aArquivo, print_r($sArquivo, TRUE));
         fclose($aArquivo);
         //}
         $oValidacao = new DBSeller_Helper_Xml_AssinaturaDigital($sArquivo);
         /**
          * Validação digital do arquivo
          */
         if (!$oValidacao->validar()) {
             throw new Exception($oValidacao->getLastError());
         }
         $oUsuario = Administrativo_Model_Usuario::getByAttribute('cnpj', $oValidacao->getCnpj());
         if (!is_object($oUsuario)) {
             throw new Exception('Usuário contribuinte não existe!', 157);
         }
         /**
          * Busca usuário contribuinte através do usuário cadastrado
          */
         $aUsuarioContribuinte = Administrativo_Model_UsuarioContribuinte::getByAttributes(array('usuario' => $oUsuario->getId(), 'cnpj_cpf' => $oUsuario->getCnpj()));
         if (!is_object($aUsuarioContribuinte[0])) {
             throw new Exception('Usuário contribuinte não encontrado!', 160);
         }
         /**
          * Seta os dados do contribuinte
          */
         $this->oDadosUsuario = $oUsuario;
         $this->oContribuinte->sCpfCnpj = $aUsuarioContribuinte[0]->getCnpjCpf();
         $this->oContribuinte->iCodigoUsuario = $oUsuario->getId();
         $this->oContribuinte->iIdUsuarioContribuinte = $aUsuarioContribuinte[0]->getId();
         /**
          * Atualiza os dados do contribuinte na sessão
          */
         $oSessao = new Zend_Session_Namespace('nfse');
         $oSessao->contribuinte = Contribuinte_Model_Contribuinte::getById($this->oContribuinte->iIdUsuarioContribuinte);
         return TRUE;
     } catch (Exception $oErro) {
         throw new Exception($oErro->getMessage(), $oErro->getCode());
     }
 }
开发者ID:arendasistemasintegrados,项目名称:mateusleme,代码行数:67,代码来源:RecepcionarLoteRps.php

示例11: getTitle

 /**
  * getTitle
  * Returns title
  * from a markdown source
  * eventually containing "====" underlined label,
  * usually parsed as <h1>
  *
  * @param string $markdown
  *
  * @return string $title
  */
 public function getTitle($markdown)
 {
     $html = "<xml>" . self::transform($markdown) . "</xml>";
     $dom = new \DOMDocument();
     $dom->loadXml($html);
     return $dom->getElementsByTagName('h1')->item(0)->nodeValue;
 }
开发者ID:ronanguilloux,项目名称:silexmarkdownserviceprovider,代码行数:18,代码来源:MarkdownExtended.php

示例12: sanitizeXml

 /**
  * Normalizes a given xml string to be compareable.
  *
  * @param string $xml
  * @return string
  */
 protected function sanitizeXml($xml)
 {
     $dom = new \DOMDocument();
     $dom->loadXml($xml);
     //$dom->normalizeDocument();
     return $dom->saveXml();
 }
开发者ID:lapistano,项目名称:wsunit,代码行数:13,代码来源:SerializerArrayTest.php

示例13: testParsing

 public function testParsing()
 {
     $collectionsJsonAtomString = file_get_contents("../data/collectionsjson.atom");
     $tagsJsonAtomString = file_get_contents("../data/tagsjson.atom");
     $doc = new DOMDocument();
     $doc->loadXml($collectionsJsonAtomString);
     $collectionfeed = new Zotero_Feed($doc);
     $this->assertEquals($collectionfeed->title, "Zotero / Z public library / Collections");
     $this->assertEquals($collectionfeed->id, "http://zotero.org/users/475425/collections?content=json");
     $this->assertEquals($collectionfeed->totalResults, 15);
     $this->assertEquals($collectionfeed->apiVersion, null);
     //deepEqual(collectionfeed.links, );
     //$this->assertEquals($collectionfeed->lastPageStart, '');
     //$this->assertEquals($collectionfeed->lastPage, 1);
     //$this->assertEquals($collectionfeed->currentPage, 1);
     $this->assertEquals($collectionfeed->dateUpdated, "2011-06-29T14:29:32Z");
     $doc = new DOMDocument();
     $doc->loadXml($tagsJsonAtomString);
     $tagsfeed = new Zotero_Feed($doc);
     $this->assertEquals($tagsfeed->title, "Zotero / Z public library / Tags");
     $this->assertEquals($tagsfeed->id, "http://zotero.org/users/475425/tags?content=json");
     $this->assertEquals($tagsfeed->totalResults, 192, "test total Results");
     $this->assertEquals($tagsfeed->apiVersion, null, "test apiVersion");
     //deepEqual(tagsfeed.links, );
     //$this->assertEquals($tagsfeed->lastPageStart, 150, "correctly found lastPageStart");
     //$this->assertEquals($tagsfeed->lastPage, 4, "correctly found lastPage");
     //$this->assertEquals($tagsfeed->currentPage, 1, "correctly found currentPage");
     $this->assertEquals($tagsfeed->dateUpdated, "2011-04-11T16:37:49Z", "found and parsed updated date");
 }
开发者ID:tnajdek,项目名称:libZotero,代码行数:29,代码来源:FeedTest.php

示例14: doRemoveNamespacedNodes

    protected function doRemoveNamespacedNodes(&$pq)
    {
        $xsl = <<<____EOF
      <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl">
          <xsl:template match="*[local-name()=name()]">
              <xsl:element name="{local-name()}">
                  <xsl:apply-templates select="@* | node()"/>
              </xsl:element>
          </xsl:template>
          <xsl:template match="@* | text()">
              <xsl:copy/>
          </xsl:template>
      </xsl:stylesheet>
____EOF;
        $xsl = \DOMDocument::loadXml($xsl);
        $proc = new \XSLTProcessor();
        $proc->importStyleSheet($xsl);
        $pq->document = $proc->transformToDoc($pq->document);
        for ($i = $pq->document->documentElement->attributes->length; $i >= 0; --$i) {
            $attr = $pq->document->documentElement->attributes->item($i);
            if (substr($attr->name, 0, 6) === 'xmlns:') {
                $pq->document->documentElement->removeAttributeNode($attr);
            }
        }
        $pq = PhpQuery::newDocumentHTML($pq->document->saveHTML());
        return $this;
    }
开发者ID:wittiws,项目名称:php-file-converters,代码行数:27,代码来源:FcHtmlBase.php

示例15: __construct

 public function __construct($xml)
 {
     $dom = new \DOMDocument();
     $dom->loadXml($xml);
     $this->domXpath = new \DOMXPath($dom);
     $this->domXpath->registerNamespace('php', 'http://php.net/xpath');
     $this->domXpath->registerPhpFunctions('strtolower');
 }
开发者ID:simonbowen,项目名称:laravel-isams,代码行数:8,代码来源:Manager.php


注:本文中的DOMDocument::loadXml方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。