public function recuperePodcast($url_flux, $nom_abonnement) { if (!empty($url_flux) && !empty($nom_abonnement)) { //On recupere le nom de l'abonnement $nom_abo = $nom_abonnement; //On recupère le flux RSS $flux = new DomDocument(); $flux->load($url_flux); $flux->preservedWhiteSpace = false; $i = 0; $pc = $flux->getElementsByTagName('item')->item($i); while (!is_null($pc)) { $titre = mysql_real_escape_string($pc->getElementsByTagName('title')->item(0)->nodeValue); $date = mysql_real_escape_string($pc->getElementsByTagName('pubDate')->item(0)->nodeValue); $desc = mysql_real_escape_string($pc->getElementsByTagName('description')->item(0)->nodeValue); $auteur = mysql_real_escape_string($pc->getElementsByTagName('author')->item(0)->nodeValue); $categ = mysql_real_escape_string($pc->getElementsByTagName('category')->item(0)->nodeValue); $url = mysql_real_escape_string($pc->getElementsByTagName('enclosure')->item(0)->getAttribute('url')); //Ajout base $sql = "INSERT INTO podcast(titre,auteur,date,description,url,id_genre,comments) VALUES('{$titre}','{$auteur}', '{$date}', '{$desc}', '{$url}', '{$categ}',' rien ')"; @mysql_query($sql) or die('Erreur requete SQL' . " " . mysql_error()); $id_podcast = mysql_insert_id(); $sql2 = "INSERT INTO abonnement(id_util,id_pod,url,nom_abo) VALUES('1','{$id_podcast}', '{$url_flux}', '{$nom_abo}')"; @mysql_query($sql2) or die('Erreur requete SQL' . " " . mysql_error()); $i = $i + 1; $pc = $flux->getElementsByTagName('item')->item($i); } } }
/** * * @param string $html */ public function exec($html) { mb_language('Japanese'); // 1.プリプロセス // scriptテキスト削除 // script内に文字列リテラルの閉じタグがあるとDomDocumentがscriptのソースを#text扱いしてしまうので // script内の文字を削除する // 正規表現で削除しようとするとSegmentation faultが発生する(StackOverFlow?)ので // simple_html_domでscript内文字列を削除 // MAX_FILE_SIZEの制限にひっかかったので、ソースを編集してデフォルトの3倍に変更している $simpleHtml = str_get_html($html); foreach ($simpleHtml->find('script') as $script) { $script->innertext = ''; } $html = $simpleHtml->outertext; // トリム // $html = preg_replace('/(\s| )+/mi', ' ', $html); // 2. dom生成 $doc = new DomDocument("1.0", "utf-8"); @$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); $node = $doc->getElementsByTagName('body')->item(0); $this->preProcessedInput = $node->textContent; // 3.プロパティを初期化 $this->domXPath = new DomXPath($doc); $this->title = @$doc->getElementsByTagName('title')->item(0)->textContent; $text = $this->scan($node); $this->textAll = $text; $this->domCountAll = $this->domCount; $this->pancutuationCountAll = $this->calcKutenScore($text) + $this->calcTotenScore($text); $this->textLengthAll = mb_strlen($text); $this->highScore = -1000000; $this->extracedNode = null; // 4.実行 $this->extract($node); }
public function buildModel($model) { try { $dom = new DomDocument(); $dom->Load($this->loadModel($model)); $rooms_base = $dom->getElementsByTagName("roomdata"); foreach ($rooms_base as $rooms_bases) { $roomtypes = $rooms_bases->getElementsByTagName("roomtype")->item(0)->nodeValue; $caption = $rooms_bases->getElementsByTagName("caption")->item(0)->nodeValue; $model_name = $rooms_bases->getElementsByTagName("model_name")->item(0)->nodeValue; $description = $rooms_bases->getElementsByTagName("description")->item(0)->nodeValue; if ($this->createRooms($roomtypes, $caption, $username, $description, $model_name)) { echo 'Done rooms<br/>'; } } foreach ($dom->getElementsByTagName("roomitem") as $room_items) { foreach ($room_items->getElementsByTagName("item") as $item) { $base_item = $item->getElementsByTagName("base_item")->item(0)->nodeValue; $x = $item->getElementsByTagName("x")->item(0)->nodeValue; $y = $item->getElementsByTagName("y")->item(0)->nodeValue; $z = $item->getElementsByTagName("z")->item(0)->nodeValue; $rot = $item->getElementsByTagName("rot")->item(0)->nodeValue; $coord = array('x' => $x, 'y' => $y, 'z' => $z); if ($this->addItemsToRooms($user_id, null, $base_item, $coord, $rot)) { echo 'Done ' . $base_item . '<br/>'; } } } } catch (Exception $e) { echo $e->getMessage(); } }
/** * Break the MODS topic element text-node metadata on * the specified character and put into seperate MODS topic elements. * * @param string $xmlsnippet The initial MODS topic element. * * @param string $breakOnCharacter The charcter break the string. * The default character is the semicolon ';'. * * @return string * An XML string containing one or more MODS topic elements. */ public function breakTopicMetadaOnCharacter($xmlsnippet, $breakOnCharacter = ';') { // Break topic metadata on ; into seperate topic elements. $xml = new \DomDocument(); $xml->loadxml($xmlsnippet, LIBXML_NSCLEAN); $topicNode = $xml->getElementsByTagName('topic')->item(0); if (!is_object($topicNode)) { $xmlstring = $xmlsnippet; } else { $topictext = $topicNode->nodeValue; $topics = explode($breakOnCharacter, $topictext); // remove old topic node. $topicNodeParent = $topicNode->parentNode; $topicNode->parentNode->removeChild($topicNode); $subjectNode = $xml->getElementsByTagName($this->topLevelNodeName)->item(0); foreach ($topics as $topic) { $topic = trim($topic); $newtopicElement = $xml->createElement('topic'); $topictextNode = $xml->createTextNode($topic); $newtopicElement->appendChild($topictextNode); $subjectNode->appendChild($newtopicElement); unset($topictextNode); unset($newtopicElement); } $xmlstring = $xml->saveXML($subjectNode); } return $xmlstring; }
/** * * @param DomDocument $index * @param DomDocument $sitemap */ protected function storeSitemap($index, $sitemap) { // Записываем текущий файл $name = sprintf('sitemap_list_%d.xml', $index->getElementsByTagName('sitemap')->length); $result = $sitemap->saveXML(); file_put_contents(FILE_PATH . $name, $result); // // $sitemapEl = $index->createElement('sitemap'); $loc = $index->createElement('loc', 'http:' . \Extasy\CMS::getWWWRoot() . 'files/' . $name); $lastMod = $index->createElement('lastmod', date('Y-m-d')); $sitemapEl->appendChild($loc); $sitemapEl->appendChild($lastMod); $index->getElementsByTagName('sitemapindex')->item('0')->appendChild($sitemapEl); }
public function getPreview($elements) { if (!isset($this->preview)) { if (!isset($elements)) { $elements = 2; } // Get just the text (no markup) from a node using $node->textContent. // Compare the textContent value to the one returned by $node->nodeValue. libxml_use_internal_errors(true); $dom = new DomDocument(); $dom->preserveWhiteSpace = false; $dom->loadHTML('<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>' . $this->Body . '</body></html>'); $dom->normalize(); $nodes = $dom->getElementsByTagName("body")->item(0)->childNodes; $elementCount = 0; $this->preview = ''; foreach ($nodes as $node) { if ($node->nodeType === XML_ELEMENT_NODE) { $this->preview .= $dom->saveXML($node); $elementCount++; if ($elementCount === $elements) { break; } } } // Carriage returns in the XML prevent the markup from validating. -- cwells $this->preview = str_replace(' ', '', $this->preview); } return $this->preview; }
public function testUpdateOnLicenceChange() { $document = $this->createTestDocument(); $document->store(); $documentCacheTable = new Opus_Db_DocumentXmlCache(); $docXmlCache = $documentCacheTable->find($document->getId(), '1')->current()->xml_data; $domDoc = new DomDocument(); $domDoc->loadXML($docXmlCache); $licences = $domDoc->getElementsByTagName('Licence'); $this->assertTrue($licences->length == 0, 'Expected no Licence element in dom.'); $licence = new Opus_Licence(); $licence->setNameLong('TestLicence'); $licence->setLinkLicence('http://example.org/licence'); $licenceId = $licence->store(); $document->setServerState('published'); $document->setLicence($licence); $docId = $document->store(); $licence = new Opus_Licence($licenceId); $licence->setNameLong('TestLicenceAltered'); $licence->store(); $docXmlCacheResult = $documentCacheTable->find($document->getId(), '1'); $this->assertTrue($docXmlCacheResult->count() == 0, 'Expected empty document xml cache'); $this->executeScript('cron-update-document-cache.php'); $docXmlCacheAfter = $documentCacheTable->find($docId, '1')->current()->xml_data; $domDocAfter = new DomDocument(); $domDocAfter->loadXML($docXmlCacheAfter); $licencesAfter = $domDocAfter->getElementsByTagName('Licence'); $this->assertTrue($licencesAfter->length == 1, 'Expected one Licence element in dom.'); $licences = $document->getLicence(); $licences[0]->delete(); }
function capi_mkfeedtitle($feed) { global $_SGLOBAL, $_SN, $_SCONFIG; $feed['title_data'] = empty($feed['title_data']) ? array() : unserialize($feed['title_data']); if (!is_array($feed['title_data'])) { $feed['title_data'] = array(); } //title $searchs = $replaces = array(); if ($feed['title_data'] && is_array($feed['title_data'])) { foreach (array_keys($feed['title_data']) as $key) { if ($key === "touser") { $dom = new DomDocument(); @$dom->loadHTML($feed["title_data"]["touser"]); $urls = $dom->getElementsByTagName('a'); $url = $urls->item(0); $value["title_data"]["touser"] = capi_fhtml($value["title_data"]["touser"]); } $searchs[] = '{' . $key . '}'; $replaces[] = $feed['title_data'][$key]; } } $searchs[] = '{actor}'; $replaces[] = empty($actors) ? $_SN[$feed['uid']] : implode(lang('dot'), $actors); $feed['title_template'] = mktarget(str_replace($searchs, $replaces, $feed['title_template'])); return $feed; }
function get_xml_droits() { if (!is_file(PATH_ROOT . 'inc/droits.xml')) { return array(); } $dom = new DomDocument("1.0", "UTF-8"); $dom->load(PATH_ROOT . 'inc/droits.xml'); $elements = $dom->getElementsByTagName('droits'); $arbre = $elements->item(0); $array_droit = array(); $sections = $arbre->childNodes; foreach ($sections as $section) { if ($section->nodeName == "section") { $nom_section = $section->attributes->getNamedItem("name")->nodeValue; $array_droit[$nom_section] = array(); $droits = $section->childNodes; foreach ($droits as $droit) { if ($droit->nodeName == "droit") { $infos_droit = $droit->childNodes; $nom_droit = $droit->getElementsByTagName("name")->item(0)->nodeValue; $type_droit = $droit->getElementsByTagName("type")->item(0)->nodeValue; $array_droit[$nom_section][$nom_droit] = array($type_droit); } } } } return $array_droit; }
public function call_success() { global $USER, $COURSE, $CFG; if (empty($this->_xmlresponse)) { if (is_siteadmin($USER->id)) { notice(get_string('adminemptyxml', 'adobeconnect'), $CFG->wwwroot . '/admin/settings.php?section=modsettingadobeconnect'); } else { notice(get_string('emptyxml', 'adobeconnect'), '', $COURSE); } } $dom = new DomDocument(); $dom->loadXML($this->_xmlresponse); $domnodelist = $dom->getElementsByTagName('status'); if ($domnodelist->item(0)->hasAttributes()) { $domnode = $domnodelist->item(0)->attributes->getNamedItem('code'); if (!is_null($domnode)) { if (0 == strcmp('ok', $domnode->nodeValue)) { return true; } else { return false; } } else { return false; } } else { return false; } }
/** * General manipulate wrapper method. * * @param string $input An XML snippet to be manipulated. We are only interested * in <abstract> snippets. * * @return string * Manipulated string */ public function manipulate($input) { $dom = new \DomDocument(); $dom->loadxml($input, LIBXML_NSCLEAN); $abstracts = $dom->getElementsByTagName('abstract'); if ($abstracts->length == 1) { $abstract = $abstracts->item(0); // Use Guzzle to hit the API. $client = new Client(); try { $original_text = urlencode($abstract->nodeValue); $query = "?text={$original_text}&format=json"; $response = $client->get($this->arrpiUrl . $query); // If there is a Guzzle error, log it and return the original snippet. } catch (Exception $e) { $this->log->addWarning("PiratizeAbstract", array('HTTP request error' => $e->getMessage())); return $input; } $body = $response->getBody(); $translation = json_decode($body, true); $abstract->nodeValue = urldecode($translation['translation']['pirate']); // Log any instances where the translation differs from the original text. if (urldecode($original_text) != $abstract->nodeValue) { $this->log->addInfo("PiratizeAbstract", array('Record key' => $this->record_key, 'Source abstract text' => urldecode($original_text), 'Piratized abstract text' => $abstract->nodeValue)); } // We're done, so return the modified snippet. return $dom->saveXML($dom->documentElement); } else { return $input; } }
/** * return the document as string. * * @access public * @return string */ public function __toString() { $this->document->formatOutput = true; $this->document->preserveWhitespace = false; $title = $this->document->createElement('title', $this->getFullTitle()); $this->head->appendChild($title); if (!empty($this->favicon)) { $favicon = $this->document->createElement('link'); $favicon->setAttribute('rel', 'shortcut icon'); $favicon->setAttribute('href', $this->favicon); $this->head->appendChild($favicon); $favicon = $this->document->createElement('link'); $favicon->setAttribute('rel', 'icon'); $favicon->setAttribute('href', $this->favicon); $this->head->appendChild($favicon); } if (!empty($this->keywords)) { $keywords = $this->document->createElement('meta'); $keywords->setAttribute('name', 'keywords'); $keywords->setAttribute('content', $this->keywords); $this->head->appendChild($keywords); } $html = $this->document->getElementsByTagName('html')->item(0); $html->appendChild($this->head); $html->appendChild($this->body); return $this->document->saveXML(); }
function get_input_tags($html) { $post_data = array(); // a new dom object $dom = new DomDocument(); //load the html into the object $dom->loadHTML($html); //discard white space $dom->preserveWhiteSpace = false; //all input tags as a list $input_tags = $dom->getElementsByTagName('input'); //get all rows from the table for ($i = 0; $i < $input_tags->length; $i++) { if (is_object($input_tags->item($i))) { $name = $value = ''; $name_o = $input_tags->item($i)->attributes->getNamedItem('name'); if (is_object($name_o)) { $name = $name_o->value; $value_o = $input_tags->item($i)->attributes->getNamedItem('value'); if (is_object($value_o)) { $value = $input_tags->item($i)->attributes->getNamedItem('value')->value; } $post_data[$name] = $value; } } } return $post_data; }
function areXmlSame($xmlString1, $xmlString2) { $document1 = new DomDocument(); $document2 = new DomDocument(); $document1->loadXML($xmlString1); $document2->loadXML($xmlString2); $allNodes1 = $document1->getElementsByTagName("*"); $allNodes2 = $document2->getElementsByTagName("*"); $length1 = $allNodes1->length; $length2 = $allNodes2->length; if ($length1 != $length2) { return false; } for ($i = 0; $i < $length1; $i++) { $node1 = $allNodes1->item($i); $node2 = $allNodes2->item($i); if (!compareAttributes($node1, $node2)) { return false; } if ($node1->nodeName != $node2->nodeName) { return false; } } return true; }
public static function getMetaTags($url) { $rc = null; try { $settings[CURLOPT_URL] = $url; $contents = self::runCurl($settings); if (!empty($contents)) { libxml_use_internal_errors(true); $doc = new \DomDocument(); $doc->loadHTML($contents); $metas = $doc->getElementsByTagName('meta'); $rc = array(); foreach ($metas as $meta) { $name = $meta->getAttribute('name'); if (empty($name)) { $name = $meta->getAttribute('property'); } $content = $meta->getAttribute('content'); if (empty($content)) { $content = $meta->getAttribute('value'); } if (!empty($name) && !empty($content)) { $rc[$name] = $content; } } } return $rc; } catch (Exception $e) { return $rc; } }
/** * @return Dto_MediaInformation|void */ public function retrieveInfo() { $mediaInfo = new Dto_MediaInformation(); $mediaInfo->setValid(false); /* * Create URL to retrive info from, for this provider * we only support direct id lookups for now */ $url = 'http://services.tvrage.com/feeds/showinfo.php?sid=' . $this->getSearchid() . '/'; list($http_code, $tvrage) = $this->_httpProvider->performCachedGet($url, false, 31 * 24 * 60 * 60); if (empty($tvrage)) { return $mediaInfo; } # if # fetch remote content $dom = new DomDocument(); $dom->preserveWhiteSpace = false; $dom->loadXML($tvrage); $showTitle = $dom->getElementsByTagName('showname'); /* * TV rage doesn't returns an 404 or something alike when the content is * not found, so we try to mimic this ourselves. */ # TVRage geeft geen 404 indien niet gevonden, dus vangen we dat zelf netjes op if (!@$showTitle->item(0)->nodeValue) { return $mediaInfo; } # if /* * Get the actual episode title */ $mediaInfo->setTitle($showTitle->item(0)->nodeValue); $mediaInfo->setValid(true); return $mediaInfo; }
/** * Return the first node in the DOM tree, or null on failure. * * @param string $tagName * @return \DOMNode|null */ protected function firstDomNode($tagName) { $nodes = $this->dom->getElementsByTagName($tagName); if ($nodes->length && ($node = $nodes->item(0))) { return $node; } return null; }
function add($key) { $url = "http://dict.cn/ws.php?utf8=true&q={$key}"; $temp_path = '/tmp/temp_codes.xml'; // Grab the XML and save it to a temporary file. This method replaces the // usual call to file() with a curl-based method. $ch = curl_init($url); $fp = fopen($temp_path, "w"); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp); // explain the XML Document. $doc = new DomDocument(1.0); $doc->load($temp_path); $defs = $doc->getElementsByTagName("def"); $audios = $doc->getElementsByTagName("audio"); $prons = $doc->getElementsByTagName("pron"); $keys = $doc->getElementsByTagName("key"); $key = $keys->item(0)->nodeValue; $def = $defs->item(0)->nodeValue; $audio = $audios->item(0)->nodeValue; $pron = $prons->item(0)->nodeValue; if ($def == "Not Found") { return false; } //”√≤È—ØµΩµƒkey¥˙ÃÊ‘≠¿¥µƒkey $this->key = $key; if (!$this->isindic($key)) { $this->addtodic($key, $audio, $pron, $def); //¿˝æ‰ $sents = $doc->getElementsByTagName("sent"); foreach ($sents as $sent) { $origs = $sent->getElementsByTagName("orig"); $orig = $origs->item(0)->nodeValue; //echo $orig."<br />"; $transes = $sent->getElementsByTagName("trans"); $trans = $transes->item(0)->nodeValue; //echo $trans."<br />"; $this->addsent($key, $orig, $trans); } } return true; }
public function testConvertsBoldTag() { $html = '<b>some text</b>'; $doc = new \DomDocument(); $doc->loadHtml($html); $tag = $doc->getElementsByTagName('b')->item(0); $parser = new \Markdownable\Tag\B(); $this->assertSame($parser->parse($tag), '**some text**'); }
public function testConvertsH6Tag() { $html = '<h6>Header 6</h6>'; $doc = new \DomDocument(); $doc->loadHtml($html); $tag = $doc->getElementsByTagName('h6')->item(0); $parser = new \Markdownable\Tag\H6(); $this->assertSame($parser->parse($tag), PHP_EOL . PHP_EOL . '###### Header 6' . PHP_EOL . PHP_EOL); }
/** * Builds the tree */ function build_tree($filter = '*') { if ($filter != '*' && strpos($filter, '/') === false) { if (strpos($filter, '.') === 0) { $filter = "//*[contains(@class,'" . substr($filter, 1) . "')]"; } elseif (strpos($filter, '#') === 0) { $filter = "//*[@id='" . substr($filter, 1) . "']"; } elseif (strpos($filter, '<') === 0) { $filter = '//' . trim($filter, ' <>'); } else { $filter = "//*[contains(@class,'" . $filter . "')]|//*[@id='" . $filter . "']|//" . trim($filter, ' <>'); } //css|id|tag } if (strpos($filter, '/') === 0) { //xpath expression $xpath = new DOMXPath($this->_dom); $entradas = @$xpath->query($filter); if ($entradas !== false) { foreach ($entradas as $entrada) { //$entrada->item($i)->nodeValue $entrada->setAttribute('class', ($entrada->hasAttribute('class') ? $entrada->getAttribute('class') . ' ' : '') . '_phpdocx_filter_paint_'); } /*$aNodos = array(); foreach($entradas as $entrada){ $aNodos[] = $entrada; } //remake domdocument $oldBody = $this->_dom->getElementsByTagName('body')->item(0); if($this->_dom->getElementsByTagName("html")->item(0)->removeChild($oldBody)){ $newBody = $this->_dom->createElement('body'); $this->_dom->getElementsByTagName("html")->item(0)->appendChild($newBody); foreach($aNodos as $nodo){ try{$this->_dom->getElementsByTagName('body')->item(0)->appendChild($nodo);} catch(Exception $e){echo($filter.' -> incorrect XPath expression.');} } }*/ } else { $filter = '*'; } //xpath expression was incorrect } if ($filter == '*') { @$this->_dom->getElementsByTagName("html")->item(0)->setAttribute('class', '_phpdocx_filter_paint_'); } $html = @$this->_dom->getElementsByTagName("html")->item(0); //all document, default if (is_null($html)) { $html = $this->_dom->firstChild; } if (is_null($html)) { throw new Exception("Requested HTML document contains no data."); } $this->_root = $this->_build_tree_r($html); }
public function testConvertsAnchorTagWithTitle() { $html = '<a href="http://example.com" title="A Link">link</a>'; $doc = new \DomDocument(); $doc->loadHtml($html); $tag = $doc->getElementsByTagName('a')->item(0); $parser = new \Markdownable\Tag\A(); $this->assertSame($parser->parse($tag), '[link](http://example.com "A Link")'); }
private function getTargetNamespace() { $this->targetNamespace = ""; /** @var DomElement[] $nodes */ $nodes = $this->dom->getElementsByTagName('definitions'); foreach ($nodes as $node) { $this->targetNamespace = $node->getAttribute('targetNamespace'); } }
public function testConvertsPTag() { $html = '<p>A paragraph of text</p>'; $doc = new \DomDocument(); $doc->loadHtml($html); $tag = $doc->getElementsByTagName('p')->item(0); $parser = new \Markdownable\Tag\P(); $this->assertSame($parser->parse($tag), PHP_EOL . PHP_EOL . 'A paragraph of text' . PHP_EOL); }
public function testConvertsHtmlBrTag() { $html = '<br>'; $doc = new \DomDocument(); $doc->loadHtml($html); $tag = $doc->getElementsByTagName('br')->item(0); $parser = new \Markdownable\Tag\Br(); $this->assertSame($parser->parse($tag), PHP_EOL); }
public function testConvertsEmTag() { $html = '<em>text</em>'; $doc = new \DomDocument(); $doc->loadHtml($html); $tag = $doc->getElementsByTagName('em')->item(0); $parser = new \Markdownable\Tag\Em(); $this->assertSame($parser->parse($tag), '*text*'); }
public function testConvertsImgTagWithTitle() { $html = '<img src="img.png" alt="alt text" title="An Image" />'; $doc = new \DomDocument(); $doc->loadHtml($html); $tag = $doc->getElementsByTagName('img')->item(0); $parser = new \Markdownable\Tag\Img(); $this->assertSame($parser->parse($tag), '![alt text](img.png "An Image")'); }
/** * gets the used xsl stylesheets. * * @access private */ function _getStyles() { $link = $this->domdoc->getElementsByTagName('link'); $i = 0; while ($link->item($i) != '') { $item = $link->item($i); if ($item->getAttributeNode('rel')->value == 'transformation') { $temp = $item->getAttributeNode('href')->value; if (substr($temp, 0, 1) == '/') { $pos = strrpos($this->doclink, '/'); $part = substr($this->doclink, 0, $pos); $this->stylelink[] = $part . $temp; } else { $this->stylelink[] = $temp; } } $i++; } }
public function rejoindrePartie() { $joueurAAjouter = $this->joueurs[0]; // --- Parcours des fichiers (d'aujourd'hui) pour trouver une partie disponible $pattern = 'XML/' . date('Y-m-d', time()) . '-partie-*-tour-0.xml'; $fichiers = glob($pattern, GLOB_BRACE); $dom = new DomDocument(); $trouve = false; foreach ($fichiers as $fichier) { // Chargement de l'xml $dom->load($fichier); // Liste des joueurs $listeJoueurs = $dom->getElementsByTagName('joueurs')->item(0); if (NULL != $listeJoueurs) { $joueurs = $listeJoueurs->getElementsByTagName('joueur'); // --- On a trouvé une partie avec 0 ou 1 seul joueur if (NULL != $joueurs && ($joueurs->length == 0 || $joueurs->length == 1 && $joueurs->item(0)->getAttribute('pseudo') != $joueurAAjouter[0])) { // --- Récupération de la partie $this->idPartie = preg_replace('!^.*partie-(\\d+)-.*$!', '$1', $fichier); $this->numero = 0; $this->joueurs[0][1] = NOIR; if ($joueurs->length == 1) { $this->joueurs[1][0] = $joueurs->item(0)->getAttribute('pseudo'); $this->joueurs[1][1] = $joueurs->item(0)->getAttribute('couleur'); } $this->etat = EN_COURS; // --- Maj du fichier XML $etat = $dom->getElementsByTagName('etat')->item(0); $etat->nodeValue = EN_COURS; // Creation nouvelle balise $nouveauJoueur = $dom->createElement('joueur'); $nouveauJoueur->setAttribute('pseudo', $this->joueurs[0][0]); $nouveauJoueur->setAttribute('couleur', $this->joueurs[0][1]); // Insertion de la nouvelle balise $listeJoueurs->appendChild($nouveauJoueur); // Enregistrement de l'xml $nouveauXml = $dom->saveXML(); if ($nouveauXml) { $trouve = true; file_put_contents($fichier, $nouveauXml); break; } } } $dernierFichier = $fichier; } // --- Aucune partie disponible -> on en créé une if (!$trouve) { $this->idPartie = preg_replace('!^.*partie-(\\d+)-.*$!', '$1', @$dernierFichier) + 1; $this->numero = 0; $this->joueurs[0][1] = BLANC; // Création de l'xml $this->getXML(); } }
function bady2cdata($html, $xml) { //Get XML params $dom = new DomDocument(); $dom->preserveWhiteSpace = FALSE; $dom->loadHtml($html); $params = $dom->getElementsByTagName('body'); foreach ($params as $k => $v) { $html = $v->nodeValue; } $params = $dom->getElementsByTagName('title'); foreach ($params as $k => $v) { $title = $v->nodeValue; } $params = $dom->getElementsByTagName('meta'); foreach ($params as $k => $v) { if ($v->getAttribute('name') == 'description') { $description = $v->getAttribute('content'); } if ($v->getAttribute('name') == 'Author') { $author = $v->getAttribute('content'); } } //Write to XML $dom = new DomDocument(); $dom->preserveWhiteSpace = FALSE; $dom->loadXML($xml); $ModulePrefs = $dom->getElementsByTagName('ModulePrefs'); foreach ($ModulePrefs as $prefs) { $prefs->setAttribute('title', $title); $prefs->setAttribute('description', $description); $prefs->setAttribute('author', $author); } $params = $dom->getElementsByTagName('Content'); foreach ($params as $k => $v) { //echo $v->nodeValue; $v->nodeValue = $html; } $s = '<?xml version="1.0" encoding="UTF-8" ?>'; $s .= $dom->saveHTML(); return $s; }