function readContent() { $data = read_xml_file($this->server, $this->port, $this->url); if (strlen($data) > 0) { $dom = new domDocument(); $dom->loadXML(substr($data, 0, strrpos($data, '>') + 1)); $arrFeeds = array(); $count = 0; foreach ($dom->getElementsByTagName('item') as $node) { if (function_exists('date_parse')) { $date_raw = date_parse($node->getElementsByTagName('pubDate')->item(0)->nodeValue); //$date = date('H:i j.m.Y', mktime($date_raw['hour'], $date_raw['minute'], $date_raw['second'], $date_raw['month'], $date_raw['day'], $date_raw['year'])); $date = date('j.m', mktime($date_raw['hour'], $date_raw['minute'], $date_raw['second'], $date_raw['month'], $date_raw['day'], $date_raw['year'])); } else { $date1 = explode(' ', $node->getElementsByTagName('pubDate')->item(0)->nodeValue); $months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); $months_n = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'); $time = explode(':', $date1[4]); //$date = $time[0] . ':' . $time[1] . ' ' . intval($date1[1]) . '.' . str_replace($months, $months_n, $date1[2]) . '.' . $date1[3]; $date = intval($date1[1]) . '.' . str_replace($months, $months_n, $date1[2]); } $itemRSS = array('title' => mb_convert_case(!$this->decodeUTF ? utf8_decode($node->getElementsByTagName('title')->item(0)->nodeValue) : $node->getElementsByTagName('title')->item(0)->nodeValue, MB_CASE_UPPER, "UTF-8"), 'description' => substr(!$this->decodeUTF ? utf8_decode($node->getElementsByTagName('description')->item(0)->nodeValue) : $node->getElementsByTagName('description')->item(0)->nodeValue, 0, 60), 'link' => $node->getElementsByTagName('link')->item(0)->nodeValue); $itemRSS['date'] = $date; array_push($arrFeeds, $itemRSS); $count++; if ($count == $this->nr_of_posts) { break; } } return $arrFeeds; } return null; }
function getCompteDisplay() { $dom = new domDocument(); $arr = array(utf8_decode('é') => "\\351", utf8_decode('è') => "\\350", utf8_decode('ç') => "\\347", utf8_decode('à') => "\\340", utf8_decode('ù') => "\\371"); $clientdata = strtr($_SESSION['client'], $arr); $dom->loadXML($clientdata); if (!$dom) { echo "Error while parsing the document\n"; exit; } $s = simplexml_import_dom($dom); return strtoupper($s->nom) . ' ' . strtoupper($s->prenom) . ',' . $s->clientid . ',' . $s->type; }
function main() { $dom = new domDocument(); $string = <<<END <a> <b>c</b> </a> END; $dom->loadXML($string); $s = simplexml_import_dom($dom); $dom = null; var_dump((string) $s->b); }
/** * * from http://www.phpro.org/examples/Get-Text-Between-Tags.html * * @get text between tags * @param string $tag The tag name * @param string $html The XML or XHTML string * @param int $strict Whether to use strict mode * @return array * */ function getTextBetweenTags($tag, $html, $strict = 0) { $dom = new domDocument(); if ($strict == 1) { $dom->loadXML($html); } else { $dom->loadHTML($html); } $dom->preserveWhiteSpace = false; $content = $dom->getElementsByTagname($tag); $out = array(); foreach ($content as $item) { $out[] = $item->nodeValue; } return $out; }
function getCompteType() { $dom = new domDocument(); $arr = array(utf8_decode('é') => "\\351", utf8_decode('è') => "\\350", utf8_decode('ç') => "\\347", utf8_decode('à') => "\\340", utf8_decode('ù') => "\\371"); $clientdata = strtr($_SESSION['client'], $arr); $dom->loadXML($clientdata); if (!$dom) { echo "Error while parsing the document\n"; exit; } $s = simplexml_import_dom($dom); if ($s->type == "client") { return "C"; } else { return "M"; } }
public function frameResponse(\FrameResponseObject $frameResponseObject) { $mplme = \steam_factory::get_object($GLOBALS["STEAM"]->get_id(), $this->id); $frameResponseObject->setTitle("Mplme"); if (isset($_REQUEST["xmlData"])) { $xmlDoc = \steam_factory::get_object_by_name($GLOBALS["STEAM"]->get_id(), $mplme->get_path() . "/data.xml"); if ($xmlDoc === 0 || !$xmlDoc instanceof \steam_document) { $xml = simplexml_load_string("<datasets></datasets>"); $xmlDoc = \steam_factory::create_document($GLOBALS["STEAM"]->get_id(), "data.xml", $xml->asXML(), "text/xml"); $xmlDoc->move($mplme); } else { $xmlRaw = $xmlDoc->get_content(); $xml = simplexml_load_string($xmlRaw); } $xmlRequest = simplexml_load_string($_REQUEST["xmlData"]); $xmlRequestDom = new \domDocument(); $xmlRequestDom->loadXML($xmlRequest->asXML()); $xmlDom = new \domDocument(); $xmlDom->loadXML($xml->asXML()); $xmlDom->documentElement->appendChild($xmlDom->importNode($xmlRequestDom->documentElement, true)); if ($_FILES && is_array($_FILES)) { foreach ($_FILES as $file) { $content = file_get_contents($file["tmp_name"]); $doc = \steam_factory::create_document($GLOBALS["STEAM"]->get_id(), $file["name"], $content, $file["type"]); $doc->move($mplme); } } $xmlDoc->set_content($xmlDom->saveXML()); //echo "<pre>" . htmlentities($xmlDom->saveXML()) . "</pre>"; echo "ok"; } else { echo "nix"; } die; //echo "done"; //$frameResponseObject->addWidget(new \Widgets\Blank()); //return $frameResponseObject; }
/** * * @get text between tags * * @param string $tag The tag name * * @param string $html The XML or XHTML string * * @param int $strict Whether to use strict mode * * @return array * */ function getTextBetweenTags($tag, $html, $strict = 0) { /*** a new dom object ***/ $dom = new domDocument(); /*** load the html into the object ***/ if ($strict == 1) { $dom->loadXML($html); } else { $dom->loadHTML($html); } /*** discard white space ***/ $dom->preserveWhiteSpace = false; /*** the tag by its tag name ***/ $content = $dom->getElementsByTagname($tag); /*** the array to return ***/ $out = array(); foreach ($content as $item) { /*** add node value to the out array ***/ $out[] = $item->nodeValue; } /*** return the results ***/ return $out; }
public function getfoafdom(&$foafurl) { $s = http::get($foafurl); if (!$s) { return false; } if (!$this->isfoaf($s)) { $foafurl = $this->discoverfoafurl($s); if (!$foafurl) { return false; } $s = http::get($foafurl); if (!$s) { return false; } if (!$this->isfoaf($s)) { return false; } } $dom = new domDocument(); $dom->loadXML($s); return $dom; }
/** * Returns the text between 2 tags * * @return array * @param string $tag The tag. * @param string $html The HTML to search in. * @param bool[optional] $strict Use strictmode? */ private function getTextBetweenTags($tag, $html, $strict = false) { // new dom document $dom = new domDocument(); // load HTML $strict == true ? $dom->loadXML($html) : $dom->loadHTML($html); // discard whitespace $dom->preserveWhiteSpace = false; // the array with results $results = array(); // fetch the tag by name $content = $dom->getElementsByTagname($tag); // loop the content foreach ($content as $item) { // add node value to results $results[] = $item->nodeValue; } // return the results return $results; }
<article id="2"> <title>Something Else Happened</title> <author>Different Person</author> </article> </articles>'; $xsl = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes" method="xml" encoding="iso-8859-1" /> <xsl:template match="/"> <xsl:apply-templates select="//article"/> </xsl:template> <xsl:template match="article"> Title: <xsl:value-of select="title"/><br /> Author: <xsl:value-of select="author"/><br /> <hr /> </xsl:template> </xsl:stylesheet>'; /* load XSLT Stylesheet */ $xslDom = new domDocument(); $xslDom->loadXML($xsl); /* load XML data */ $xmlDom = new domDocument(); $xmlDom->loadXML($xml); $xsl = new XsltProcessor(); // instantiate XSLT processor $xsl->importStylesheet($xslDom); // load stylesheet echo $xsl->transformToXML($xmlDom); // perform the transformation & return HTML
static function importBooksXML($files_name_pars, $catid) { $files_name_pars = file($files_name_pars); $files_name_pars = implode('', $files_name_pars); //echo $files_name_pars; global $database; $retVal = array(); $new_categories = array(); $k = 0; $dom = new domDocument('1.0', 'utf-8'); $dom->loadXML($files_name_pars); $version = $dom->getElementsByTagName('version'); if ($version->item(0) != NULL) { $numversion = explode(' ', $version->item(0)->nodeValue); if (intval($numversion[0]) >= 2) { $categories_xml = $dom->getElementsByTagName('category'); if ($categories_xml->item(0) != NULL) { //�µÑ��»�¸ �² XML �µÑ�Ñ‚ÑŒ Ñ��¿�¸Ñ��¾�º �º�°Ñ‚�µÑ€�¾�³�¸�¹ �´�»Ñ� �¸�¼�¿�¾Ñ€Ñ‚�° mosBooklibraryImportExport::remove_info(); //ч�¸Ñ�Ñ‚�¸�¼ �±�°�·Ñƒ �´�°�½�½Ñ‹Ñ… if ($catid === null) { //�µÑ��»�¸ �º�°Ñ‚�µ�³�¾Ñ€�¸Ñ� �´�»Ñ� �¸�¼�¿�¾Ñ€Ñ‚�° �½�µ �²Ñ‹�±Ñ€�°�½�° for ($i = 0; $i < $categories_xml->length; $i++) { $category = $categories_xml->item($i); $new_category = new stdClass(); $new_category->old_id = mosBooklibraryImportExport::getXMLItemValue($category, 'id'); $new_category->old_parent_id = mosBooklibraryImportExport::getXMLItemValue($category, 'parent_id'); $new_category->name = mosBooklibraryImportExport::getXMLItemValue($category, 'name'); $new_category->title = mosBooklibraryImportExport::getXMLItemValue($category, 'title'); $new_category->alias = mosBooklibraryImportExport::getXMLItemValue($category, 'alias'); $new_category->published = mosBooklibraryImportExport::getXMLItemValue($category, 'published'); $new_category->ordering = mosBooklibraryImportExport::getXMLItemValue($category, 'ordering'); $new_category->access = mosBooklibraryImportExport::getXMLItemValue($category, 'access'); $new_category->description = mosBooklibraryImportExport::getXMLItemValue($category, 'description'); $new_category->params = mosBooklibraryImportExport::getXMLItemValue($category, 'params'); $new_category->params2 = mosBooklibraryImportExport::getXMLItemValue($category, 'params2'); $new_category = mosBooklibraryImportExport::findCategory($new_categories, $new_category); } } mosBooklibraryImportExport::refreshCategoryParentId($new_categories); } //end if exist categories //exit; $books_xml = $dom->getElementsByTagName('book'); foreach ($books_xml as $i => $book_xml) { //echo mosBooklibraryImportExport::getXMLItemValue($book_xml,'bookid'); $book = new mosBooklibrary($database); //get BookID $book->bookid = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'bookid'); //get ISBN $book->isbn = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'isbn'); //get Title(book) $book->title = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'title'); //get Authors $book->authors = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'authors'); //get Manufacturer $book->manufacturer = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'manufacturer'); //get releasedate $book->release_Date = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'releaseDate'); //get language $book->language = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'language'); $book->langshow = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'langshow'); if ($book->langshow == "") { $book->langshow = "*"; } //get hits $book->hits = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'hits'); $book->user_name = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'user_name'); //get featured_clicks $book->featured_clicks = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'featured_clicks'); //get featured_shows $book->featured_shows = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'featured_shows'); //get rating $book->rating = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'rating'); //get price $book->price = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'price'); //get priceunit $book->priceunit = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'priceunit'); //get URL $book->URL = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'url'); //get imageURL $book->imageURL = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'imageURL'); //get edition $book->edition = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'edition'); //get ebookURL $book->ebookURL = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'ebookURL'); //get informationFrom $book->informationFrom = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'informationFrom'); //get date $book->date = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'date'); //get published $book->published = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'published'); //get comment $book->comment = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'comment'); //get numberOfPages $book->numberOfPages = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'numberOfPages'); $book->comment = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'comment'); //get email owner book $book->owneremail = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'owneremail'); //get email owner book $book->owner_id = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'owner_id'); //get email owner book $book->vm_id_product = mosBooklibraryImportExport::getXMLItemValue($book_xml, 'vm_id_product'); //get Categorie if ($catid != "0" && $catid != "") { //�µÑ��»�¸ �²Ñ‹�±Ñ€�°�½ �¸�¼�¿�¾Ñ€Ñ‚ �² �º�°Ñ‚�µ�³�¾Ñ€�¸ÑŽ $book->categs = array($catid); } else { $categ = $book_xml->getElementsByTagName('categ'); //var_dump($categ); $arrcatid = array(); foreach ($categ as $cattemp) { //Ñ��¿�¸Ñ��¾�º �º�°Ñ‚�µ�³�¾Ñ€�¸�¹ �º�½�¸�³ �¸�· XML $category_book_old_id = $cattemp->nodeValue; //n-�°Ñ� �º�°Ñ‚�µ�³�¾Ñ€�¸Ñ� �º�½�¸�³�¸ �¸�· XML foreach ($new_categories as $new_category) { //�¸Ñ‰�µ�¼ �² Ñ��¿�¸Ñ��º�µ Ñ��¾�·�´�°�½�½Ñ‹Ñ… �º�°Ñ‚�µ�³�¾Ñ€�¸�¹ if ($new_category->old_id == $category_book_old_id) { $arrcatid[] = $new_category->id; } } } $book->categs = $arrcatid; } $tmp[] = $i; $tmp[] = $book->bookid; $tmp[] = $book->isbn; $tmp[] = $book->title; $tmp[] = $book->authors; $tmp[] = $book->manufacturer; if (!$book->check()) { $tmp[] = $book->getError(); $retVal[$i] = $tmp; unset($tmp); continue; } if (!$book->store()) { $tmp[] = $book->getError(); $retVal[$i] = $tmp; unset($tmp); continue; } else { $book->saveCategs(); $tmp[] = "OK"; //save categ //get Reviews if (mosBooklibraryImportExport::getXMLItemValue($book_xml, 'reviews') != "") { $review_list = $book_xml->getElementsByTagName('review'); for ($j = 0; $j < $review_list->length; $j++) { $review = $review_list->item($j); //get for review - fk_bookid == #__booklibrary.id /* $database->setQuery("SELECT id FROM #__booklibrary ". "\n WHERE isbn = '".$book->isbn."';"); $fk_bookid = $database->loadResult();*/ $fk_bookid = $book->id; //get for review - fk_userid $review_fk_userid = mosBooklibraryImportExport::getXMLItemValue($review, 'fk_userid'); //check - exist this user or not - if don't exist set he as anonymous $database->setQuery("SELECT id FROM #__users " . "\n WHERE id = " . $review_fk_userid . ";"); $review_fk_userid = $database->loadResult(); if (count($review_fk_userid) == 0) { $review_fk_userid = 0; } //get for review - date $review_date = mosBooklibraryImportExport::getXMLItemValue($review, 'date'); //get for review - rating $review_rating = mosBooklibraryImportExport::getXMLItemValue($review, 'rating'); //get for review - title $review_title = mosBooklibraryImportExport::getXMLItemValue($review, 'title'); //get for review - comment $review_comment = mosBooklibraryImportExport::getXMLItemValue($review, 'comment'); //insert data in table #__booklibrary_review if (version_compare(JVERSION, "3.3.0", "ge")) { $database->setQuery("INSERT INTO #__booklibrary_review" . "\n (fk_bookid, fk_userid, date, rating, title, comment)" . "\n VALUES " . "\n (" . $database->Quote($fk_bookid) . ",\n " . $database->Quote($review_fk_userid) . ",\n " . $database->Quote($review_date) . ",\n " . $database->Quote($review_rating) . ",\n " . $database->Quote($review_title) . ",\n " . $database->Quote($review_comment) . ");"); } else { $database->setQuery("INSERT INTO #__booklibrary_review" . "\n (fk_bookid, fk_userid, date, rating, title, comment)" . "\n VALUES " . "\n (" . $fk_bookid . ",\n " . $review_fk_userid . ",\n '" . $review_date . "',\n " . $review_rating . ",\n '" . $review_title . "',\n '" . $review_comment . "');"); } $database->query(); } //end for(...) - REVIEW } //end if(...) - REVIEW //***********************************************efiles ************************************************** if (mosBooklibraryImportExport::getXMLItemValue($book_xml, 'ebook') != "") { $ebook_list = $book_xml->getElementsByTagName('ebook'); for ($j = 0; $j < $ebook_list->length; $j++) { $efile = $ebook_list->item($j); $fk_bookid = $book->id; $efileLoc = mosBooklibraryImportExport::getXMLItemValue($efile, 'location'); $efileDesc = mosBooklibraryImportExport::getXMLItemValue($efile, 'description'); //insert data in table #__booklibrary_files $database->setQuery("INSERT INTO #__booklibrary_files" . "\n (fk_book_id, location, description)" . "\n VALUES " . "\n (" . $fk_bookid . ",\n '" . $efileLoc . "',\n '" . $efileDesc . "');"); $database->query(); } //end for(...) - EFILES } //end if(...) - EFILES //************************************************end efiles*********************************************** $book->checkin(); //$book->updateOrder( "catid='$book->catid'" ); $retVal[$i] = $tmp; } //echo $i,':';var_dump($tmp); echo '<br/>'; unset($tmp); continue; } //end foreach books */ } // end if version >2.0 } else { // ----- OLD VERSION------ //exit; $st = $bookid = ""; $begin = $end = $kol = 0; $book_list = $dom->getElementsByTagName('book'); for ($i = 0; $i < $book_list->length; $i++) { $book_class = new mosBookLibrary($database); $book = $book_list->item($i); // echo $book_item->hasChildNodes() . "<br />"; //get BookID $book_id = $book_class->bookid = 1 + $book_class->getMaxBookid(); //mosBooklibraryImportExport::getXMLItemValue($book,'bookid'); //get ISBN $book_isbn = $book_class->isbn = mosBooklibraryImportExport::getXMLItemValue($book, 'isbn'); //get Title(book) $book_title = $book_class->title = mosBooklibraryImportExport::getXMLItemValue($book, 'title'); //get Authors $book_authors = $book_class->authors = mosBooklibraryImportExport::getXMLItemValue($book, 'authors'); //get Manufacturer $book_manufacturer = $book_class->manufacturer = mosBooklibraryImportExport::getXMLItemValue($book, 'manufacturer'); //get releasedate $book_class->release_Date = mosBooklibraryImportExport::getXMLItemValue($book, 'releaseDate'); //get hits $book_class->hits = mosBooklibraryImportExport::getXMLItemValue($book, 'hits'); $book_class->user_name = mosBooklibraryImportExport::getXMLItemValue($book, 'user_name'); //get rating $book_class->rating = mosBooklibraryImportExport::getXMLItemValue($book, 'rating'); //get featured_clicks $book_class->featured_clicks = mosBooklibraryImportExport::getXMLItemValue($book, 'featured_clicks'); //get featured_shows $book_class->featured_shows = mosBooklibraryImportExport::getXMLItemValue($book, 'featured_shows'); //get price $book_class->price = mosBooklibraryImportExport::getXMLItemValue($book, 'price'); if (substr($book_class->price, 0, 1) == "\$") { $book_class->price = substr($book_class->price, 1); $book_class->priceunit = 'USD'; } //get URL $book_class->URL = mosBooklibraryImportExport::getXMLItemValue($book, 'url'); //get imageURL $book_class->imageURL = mosBooklibraryImportExport::getXMLItemValue($book, 'imageURL'); //get edition $book_class->edition = mosBooklibraryImportExport::getXMLItemValue($book, 'edition'); //get ebookURL $book_class->ebookURL = mosBooklibraryImportExport::getXMLItemValue($book, 'ebookURL'); //get informationFrom $book_class->informationFrom = mosBooklibraryImportExport::getXMLItemValue($book, 'informationFrom'); //get date $book_class->date = mosBooklibraryImportExport::getXMLItemValue($book, 'date'); //get comment $book_class->comment = mosBooklibraryImportExport::getXMLItemValue($book, 'comment'); //get Categorie $book_class->categs = array($catid); //get Language $book_class->language = mosBooklibraryImportExport::getXMLItemValue($book, 'language'); $book_class->langshow = mosBooklibraryImportExport::getXMLItemValue($book, 'langshow'); if ($book_class->langshow == "") { $book_class->langshow = "*"; } //get Comment for book (item Book Description) $book_class->comment = mosBooklibraryImportExport::getXMLItemValue($book, 'comment'); //get vm_id_product $book_class->vm_id_product = mosBooklibraryImportExport::getXMLItemValue($book, 'vm_id_product'); //for output rezult in table $tmp[0] = $i; $tmp[1] = $book_id; $tmp[2] = $book_isbn; $tmp[3] = $book_title; $tmp[4] = $book_authors; $tmp[5] = $book_manufacturer; if (!$book_class->check()) { $tmp[6] = $book_class->getError(); $retVal[$i] = $tmp; continue; } if (!$book_class->store()) { $tmp[6] = $book_class->getError(); $retVal[$i] = $tmp; continue; } else { $tmp[6] = "OK"; $book_class->saveCategs(); } //***********************************************efiles ************************************************** if (mosBooklibraryImportExport::getXMLItemValue($book_xml, 'ebook') != "") { $ebook_list = $book_xml->getElementsByTagName('ebook'); for ($j = 0; $j < $ebook_list->length; $j++) { $efile = $ebook_list->item($j); $fk_bookid = $book->id; $efileLoc = mosBooklibraryImportExport::getXMLItemValue($efile, 'location'); $efileDesc = mosBooklibraryImportExport::getXMLItemValue($efile, 'description'); //insert data in table #__booklibrary_files $database->setQuery("INSERT INTO #__booklibrary_files" . "\n (fk_book_id, location, description)" . "\n VALUES " . "\n (" . $fk_bookid . ",\n '" . $efileLoc . "',\n '" . $efileDesc . "');"); $database->query(); } //end for(...) - EFILES } //end if(...) - EFILES //************************************************end efiles*********************************************** $book_class->checkin(); //$book_class->updateOrder( "catid='$book_class->catid'" ); $retVal[$i] = $tmp; //get Reviews if ($tmp[6] == "OK" && mosBooklibraryImportExport::getXMLItemValue($book, 'reviews') != "") { $review_list = $book->getElementsByTagname('review'); for ($j = 0; $j < $review_list->length; $j++) { $review = $review_list->item($j); //get for review - fk_bookid == #__booklibrary.id /* $database->setQuery("SELECT id FROM #__booklibrary ". "\n WHERE isbn = '".$book_isbn."';"); $fk_bookid = $database->loadResult();*/ $fk_bookid = $book_class->id; //get for review - fk_userid $review_fk_userid = mosBooklibraryImportExport::getXMLItemValue($review, 'fk_userid'); //check - exist this user or not - if don't exist set he as anonymous $database->setQuery("SELECT id FROM #__users " . "\n WHERE id = " . $review_fk_userid . ";"); $review_fk_userid = $database->loadResult(); if (count($review_fk_userid) == 0) { $review_fk_userid = 0; } //get for review - date $review_date = mosBooklibraryImportExport::getXMLItemValue($review, 'date'); //get for review - rating $review_rating = mosBooklibraryImportExport::getXMLItemValue($review, 'rating'); //get for review - title $review_title = mosBooklibraryImportExport::getXMLItemValue($review, 'title'); //get for review - comment $review_comment = mosBooklibraryImportExport::getXMLItemValue($review, 'comment'); //insert data in table #__booklibrary_review if (version_compare(JVERSION, "3.3.0", "ge")) { $database->setQuery("INSERT INTO #__booklibrary_review" . "\n (fk_bookid, fk_userid, date, rating, title, comment)" . "\n VALUES " . "\n (" . $database->Quote($fk_bookid) . ",\n " . $database->Quote($review_fk_userid) . ",\n " . $database->Quote($review_date) . ",\n " . $database->Quote($review_rating) . ",\n " . $database->Quote($review_title) . ",\n " . $database->Quote($review_comment) . ");"); } else { $database->setQuery("INSERT INTO #__booklibrary_review" . "\n (fk_bookid, fk_userid, date, rating, title, comment)" . "\n VALUES " . "\n (" . $fk_bookid . ",\n " . $review_fk_userid . ",\n '" . $review_date . "',\n " . $review_rating . ",\n '" . $review_title . "',\n '" . $review_comment . "');"); } $database->query(); } //end for(...) - REVIEW } } //end for(...) - BOOK } //var_dump($retVal); exit; return $retVal; }
protected function get_items_datas($items) { $datas = array(); foreach ($items as $item) { $informations = array(); $notice = new notice($item); //s'agit-il d'une notice de flux RSS ? $eformat = array(); $eformat = explode(' ', $notice->eformat); if ($eformat[0] == 'RSS' && $notice->lien != '') { @ini_set("zend.ze1_compatibility_mode", "0"); $loaded = false; $aCurl = new Curl(); $aCurl->timeout = 2; $content = $aCurl->get($notice->lien); $flux = $content->body; if ($flux && $content->headers['Status-Code'] == 200) { $rss = new domDocument(); $old_errors_value = false; if (libxml_use_internal_errors(true)) { $old_errors_value = true; } $loaded = $rss->loadXML($flux); } if (!count(libxml_get_errors())) { if ($loaded) { //les infos sur le flux... //Flux RSS if ($rss->getElementsByTagName("channel")->length > 0) { $channel = $rss->getElementsByTagName("channel")->item(0); $elements = array('url'); $informations = $this->get_informations($channel, $elements, 1); //on va lire les infos des items... $informations['items'] = array(); $rss_items = $rss->getElementsByTagName("item"); $elements = array('title', 'description', 'link', 'pubDate', 'category'); for ($i = 0; $i < $rss_items->length; $i++) { if ($this->parameters['nb_max_elements'] == 0 || $i < $this->parameters['nb_max_elements']) { $informations['items'][] = $this->get_informations($rss_items->item($i), $elements, false); } } //Flux ATOM } elseif ($rss->getElementsByTagName("feed")->length > 0) { $feed = $rss->getElementsByTagName("feed")->item(0); $atom_elements = array('url'); $informations = $this->get_atom_informations($feed, $atom_elements, 1); //on va lire les infos des entries... $informations['items'] = array(); $entries = $rss->getElementsByTagName("entry"); $atom_elements = array('title', 'link', 'published', 'content'); for ($i = 0; $i < $entries->length; $i++) { if ($this->parameters['nb_max_elements'] == 0 || $i < $this->parameters['nb_max_elements']) { $informations['items'][] = $this->get_atom_informations($entries->item($i), $atom_elements, false); } } } foreach ($informations['items'] as $rss_item) { $data = array(); $data["num_notice"] = "0"; $data["type"] = "rss"; $data["title"] = $rss_item["title"]; $data["summary"] = $rss_item["description"]; $data["content"] = $rss_item["description"]; $data["url"] = $rss_item["link"]; $data["publication_date"] = date('Y-m-d h:i:s', strtotime($rss_item["pubDate"])); $data["logo_url"] = $informations["url"]; $data["descriptors"] = ""; if (is_array($rss_item["category"])) { $data["tags"] = array_map("strip_tags", $rss_item["category"]); } else { $data["tags"] = strip_tags($rss_item["category"]); } $datas[] = $data; } } } else { libxml_clear_errors(); } libxml_use_internal_errors($old_errors_value); @ini_set("zend.ze1_compatibility_mode", "1"); return $datas; } } return false; }
require_once '../../api/Simpla.php'; $simpla = new Simpla(); //$category_id = $simpla->request->get('category_id', 'integer'); //$product_id = $simpla->request->get('product_id', 'integer'); //курс с сайта ЦБ РФ $corrency_output = array(); $date = date("d/m/Y"); // Сегодняшняя дата в необходимом формате $link = "http://www.cbr.ru/scripts/XML_daily.asp?date_req={$date}"; // Ссылка на XML-файл с курсами валют $content = file_get_contents($link); // Скачиваем содержимое страницы $dom = new domDocument("1.0", "cp1251"); // Создаём DOM $dom->loadXML($content); // Загружаем в DOM XML-документ $root = $dom->documentElement; // Берём корневой элемент $childs = $root->childNodes; // Получаем список дочерних элементов $data = array(); // Набор данных for ($i = 0; $i < $childs->length; $i++) { $childs_new = $childs->item($i)->childNodes; // Берём дочерние узлы for ($j = 0; $j < $childs_new->length; $j++) { /* Ищем интересующие нас валюты */ $el = $childs_new->item($j); $code = $el->nodeValue; if ($code == "USD" || $code == "EUR") {
function get_corrency() { //тест курс доллара по цб $corrency_output = array(); $date = date("d/m/Y"); // Сегодняшняя дата в необходимом формате $link = "http://www.cbr.ru/scripts/XML_daily.asp?date_req={$date}"; // Ссылка на XML-файл с курсами валют $content = file_get_contents($link); // Скачиваем содержимое страницы $dom = new domDocument("1.0", "cp1251"); // Создаём DOM $dom->loadXML($content); // Загружаем в DOM XML-документ $root = $dom->documentElement; // Берём корневой элемент $childs = $root->childNodes; // Получаем список дочерних элементов $data = array(); // Набор данных for ($i = 0; $i < $childs->length; $i++) { $childs_new = $childs->item($i)->childNodes; // Берём дочерние узлы for ($j = 0; $j < $childs_new->length; $j++) { /* Ищем интересующие нас валюты */ $el = $childs_new->item($j); $code = $el->nodeValue; if ($code == "USD" || $code == "EUR") { $data[] = $childs_new; } // Добавляем необходимые валюты в массив } } /* Перебор массива с данными о валютах */ for ($i = 0; $i < count($data); $i++) { $list = $data[$i]; for ($j = 0; $j < $list->length; $j++) { $el = $list->item($j); /* Выводим курсы валют */ if ($el->nodeName == "Name") { $corrency_output[$i]->key = $el->nodeValue . " - "; } elseif ($el->nodeName == "Value") { $corrency_output[$i]->val = $el->nodeValue . "р."; } } } $this->design->assign("corrency_cbrf", $corrency_output); //get products //$this->design->smarty->registerPlugin("function", "get_products", array($this, 'get_products_plugin')); //тест }
<?php $xmlstring = '<?xml version="1.0" ?> <!DOCTYPE books [ <!ATTLIST book id ID #IMPLIED> ]> <books> <book id="1"> <title>Book 1</title> </book> <book id="2"> <title>Book 2</title> </book> </books>'; $dom = new domDocument(); /* load XML from string */ $dom->loadXML($xmlstring); /* get the node identified by id #2 */ $node = $dom->getElementById("2"); print trim($node->nodeValue);
public function get_billing_post() { //mycard主动导入前十分钟数据的接口 $data = $this->CI->input->post('data'); $ip = $this->CI->input->ip_address(); $buchu_order['data'] = $data; $buchu_order['time'] = time(); $buchu_order['ip'] = $ip; $buchu_order['xml_data'] = 0; $buchu_res = $this->insert_buchu_order($buchu_order); if (!in_array($ip, $this->allowed_ips)) { var_dump($ip); var_dump("access denied"); return FALSE; } /*$data = ' <BillingApplyRq> <FatoryId>syd</FatoryId> <TotalNum>2</TotalNum> <Records> <Record> <ReturnMsgNo>1</ReturnMsgNo> <ReturnMsg></ReturnMsg> <TradeSeq>1755395928</TradeSeq> </Record> <Record> <ReturnMsgNo>1</ReturnMsgNo> <ReturnMsg></ReturnMsg> <TradeSeq>1234235355</TradeSeq> </Record> </Records> </BillingApplyRq> ';*/ $dom = new domDocument(); $dom->loadXML($data); $s = simplexml_import_dom($dom); for ($i = 0; $i < $s->TotalNum; $i++) { $Recode = $s->Records->Record[$i]; $TradeSeq = (string) $Recode->TradeSeq; $temp_order = $this->get_recharge_order($TradeSeq); if (empty($temp_order)) { continue; } foreach ($temp_order as $key => $item) { $this->order[$key] = $item; } $merchant_data = $this->pay_model->get_merchant_data_by_id($this->order['merchant_id']); $this->FatoryId = trim($merchant_data[0]->merchant_name); if ($this->FatoryId != trim((string) $s->FatoryId)) { continue; } if ($this->order_status['recharging'] == $this->order['order_status']) { $check_order = $this->get_billing_order_info($this->order['auth_code']); if (1 != $check_order[0]) { $log = array('order_id' => $this->order['order_id'], 'order_status' => $this->order_status['recharging'], 'recharge_step' => $this->recharge_step['get_recharge_result'], 'tradeseq' => $this->order['tradeseq'], 'err_no' => $check_order[0], 'err_msg' => empty($check_order[1]) ? '' : $check_order[1], 'time' => time()); $this->insert_err_log($log); continue; } $result = $this->ask_for_payment($Recode->ReturnMsgNo); if ($result) { $res_service = $this->_offer_service($this->order['order_sn']); //提供充值游戏币服务 uid 为标记 if ($res_service['status']) { $this->order['offer_time'] = time(); $this->order['offer_yuanbao'] = 1; $this->update_order(); } } } else { //not the right order status continue; } } }
function generateOCR($pageName) { if ($this->file_exists($this->get_file_path("X/" . $pageName . ".xml.gz"))) { $filepath = $this->get_file($this->get_file_path("X/" . $pageName . ".xml.gz")); print $file_path; ob_start(); readgzfile($filepath); $file = ob_get_clean(); $xml = new domDocument("1.0", "iso-8859-1"); $xml->loadXML($file); $styleNodes = $xml->getElementsByTagName("Styles")->item(0); $styles = array(); if ($styleNodes->childNodes->length > 0) { foreach ($styleNodes->childNodes as $style) { foreach ($style->attributes as $name => $attrNode) { if ($name == 'FONTSTYLE') { switch ($attrNode->value) { case "bold": $fontstyle = "B"; break; case "italics": $fontstyle = "I"; break; default: $fontstyle = ""; break; } $styles[$style->getAttribute("ID")][$name] = trim($fontstyle); } else { if ($name == "FONTFAMILY") { switch (trim($attrNode->value)) { case "TIMES NEW ROMAN": $styles[$style->getAttribute("ID")][$name] = "times"; break; case "COURIER NEW": $styles[$style->getAttribute("ID")][$name] = "courier"; break; default: $styles[$style->getAttribute("ID")][$name] = "arial"; break; } } else { if ($name != 'ID') { switch ($attrNode->value) { case "bold": $fontstyle = "B"; break; case "italics": $fontstyle = "I"; break; default: $fontstyle = ""; break; } $styles[$style->getAttribute("ID")][$name] = trim($attrNode->value); } } } } } } $printSpaces = $xml->getElementsByTagName("PrintSpace"); foreach ($printSpaces as $printSpace) { //block de texte... $textBlocks = $printSpace->getElementsByTagName('TextBlock'); foreach ($textBlocks as $textBlock) { $block = array(); foreach ($textBlock->attributes as $name => $attrNode) { $block[$name] = $attrNode->value; } $align = substr($styles[$block['STYLEREFS']]['ALIGN'], 0, 1); //ligne d'un block $textLignes = $textBlock->getElementsByTagName('TextLine'); foreach ($textLignes as $textLine) { foreach ($textLine->attributes as $name => $attrNode) { $line[$name] = $attrNode->value; } //style de la ligne $line['CONTENT'] = ""; foreach ($textLine->childNodes as $child) { if ($child->nodeName == "String" && $child->getAttribute("STYLEREFS") != $line['STYLEREFS'] || $child->nodeName == "SP") { $line['WIDTH'] = $child->getAttribute("HPOS") - $line['HPOS']; if ($child->nodeName == "SP") { $line['CONTENT'] .= " "; $line['WIDTH'] += $child->getAttribute("WIDTH"); } $this->convert->setY($this->convert->convertPxToMm($line['VPOS'])); $this->convert->setX($this->convert->convertPxToMm($line['HPOS'])); $this->convert->SetFont($styles[$line['STYLEREFS']]['FONTFAMILY'], $styles[$line['STYLEREFS']]['FONTSTYLE'], $styles[$line['STYLEREFS']]['FONTSIZE']); $this->convert->Cell($this->convert->convertPxToMm($line['WIDTH']), $this->convert->convertPxToMm($line['HEIGHT']), utf8_decode($line['CONTENT']), 0, 0, $align); if ($child->nodeName != "SP") { $line['STYLEREFS'] = $child->getAttribute("STYLEREFS"); } $line['CONTENT'] = ""; $line['HPOS'] = $line['HPOS'] + $line['WIDTH']; } switch ($child->nodeName) { case "String": $line['CONTENT'] .= $child->getAttribute("CONTENT"); $width = $child->getAttribute("WIDTH"); break; } } if ($line['CONTENT']) { $line['WIDTH'] = $width; $this->convert->setY($this->convert->convertPxToMm($line['VPOS'])); $this->convert->setX($this->convert->convertPxToMm($line['HPOS'])); $this->convert->SetFont($styles[$line['STYLEREFS']]['FONTFAMILY'], $styles[$line['STYLEREFS']]['FONTSTYLE'], $styles[$line['STYLEREFS']]['FONTSIZE']); $this->convert->Cell($this->convert->convertPxToMm($line['WIDTH']), $this->convert->convertPxToMm($line['HEIGHT']), utf8_decode($line['CONTENT']) . " ", 0, 0, $align); $this->textContent .= " " . utf8_decode($line['CONTENT']); } } } } } }
* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ include_once 'wsf.php'; $requestPayloadString = <<<XML <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples"> <text>Hello World!</text> </ns1:echoString> XML; $document = new domDocument(); $document->loadXML($requestPayloadString); try { $responseMessage = ws_request($document, array("to" => "http://localhost/samples/reply_echo_service.php")); printf("Response = %s <br>", htmlspecialchars($responseMessage->str)); } catch (Exception $e) { if ($e instanceof WSFault) { printf("Soap Fault: %s\n", $e->Reason); } else { printf("Message = %s\n", $e->getMessage()); } }
public function fetch() { // Обработка действий if ($this->request->method('post')) { foreach ($this->request->post('currency') as $n => $va) { foreach ($va as $i => $v) { if (empty($currencies[$i])) { $currencies[$i] = new stdClass(); } $currencies[$i]->{$n} = $v; } } $currencies_ids = array(); foreach ($currencies as $currency) { if ($currency->id) { $this->money->update_currency($currency->id, $currency); } else { $currency->id = $this->money->add_currency($currency); } $currencies_ids[] = $currency->id; } // Удалить непереданные валюты $query = $this->db->placehold('DELETE FROM __currencies WHERE id NOT IN(?@)', $currencies_ids); $this->db->query($query); // Пересчитать курсы $old_currency = $this->money->get_currency(); $new_currency = reset($currencies); if ($old_currency->id != $new_currency->id) { $coef = $new_currency->rate_from / $new_currency->rate_to; if ($this->request->post('recalculate') == 1) { $this->db->query("UPDATE __variants SET price=price*?", $coef); $this->db->query("UPDATE __delivery SET price=price*?, free_from=free_from*?", $coef, $coef); $this->db->query("UPDATE __orders SET delivery_price=delivery_price*?", $coef); $this->db->query("UPDATE __orders SET total_price=total_price*?", $coef); $this->db->query("UPDATE __purchases SET price=price*?", $coef); $this->db->query("UPDATE __coupons SET value=value*? WHERE type='absolute'", $coef); $this->db->query("UPDATE __coupons SET min_order_price=min_order_price*?", $coef); $this->db->query("UPDATE __orders SET coupon_discount=coupon_discount*?", $coef); } $this->db->query("UPDATE __currencies SET rate_from=1.0*rate_from*{$new_currency->rate_to}/{$old_currency->rate_to}"); $this->db->query("UPDATE __currencies SET rate_to=1.0*rate_to*{$new_currency->rate_from}/{$old_currency->rate_from}"); $this->db->query("UPDATE __currencies SET rate_to = rate_from WHERE id=?", $new_currency->id); $this->db->query("UPDATE __currencies SET rate_to = 1, rate_from = 1 WHERE (rate_to=0 OR rate_from=0) AND id=?", $new_currency->id); } // Отсортировать валюты asort($currencies_ids); $i = 0; foreach ($currencies_ids as $currency_id) { $this->money->update_currency($currencies_ids[$i], array('position' => $currency_id)); $i++; } // Действия с выбранными $action = $this->request->post('action'); $id = $this->request->post('action_id'); if (!empty($action) && !empty($id)) { switch ($action) { case 'disable': $this->money->update_currency($id, array('enabled' => 0)); break; case 'enable': $this->money->update_currency($id, array('enabled' => 1)); break; case 'show_cents': $this->money->update_currency($id, array('cents' => 2)); break; case 'hide_cents': $this->money->update_currency($id, array('cents' => 0)); break; case 'delete': $this->money->delete_currency($id); break; } } } //курс с сайта ЦБ РФ $corrency_output = array(); $date = date("d/m/Y"); // Сегодняшняя дата в необходимом формате $link = "http://www.cbr.ru/scripts/XML_daily.asp?date_req={$date}"; // Ссылка на XML-файл с курсами валют $content = file_get_contents($link); // Скачиваем содержимое страницы $dom = new domDocument("1.0", "cp1251"); // Создаём DOM $dom->loadXML($content); // Загружаем в DOM XML-документ $root = $dom->documentElement; // Берём корневой элемент $childs = $root->childNodes; // Получаем список дочерних элементов $data = array(); // Набор данных for ($i = 0; $i < $childs->length; $i++) { $childs_new = $childs->item($i)->childNodes; // Берём дочерние узлы for ($j = 0; $j < $childs_new->length; $j++) { /* Ищем интересующие нас валюты */ $el = $childs_new->item($j); $code = $el->nodeValue; if ($code == "USD" || $code == "EUR") { $data[] = $childs_new; } // Добавляем необходимые валюты в массив } } /* Перебор массива с данными о валютах */ for ($i = 0; $i < count($data); $i++) { $list = $data[$i]; for ($j = 0; $j < $list->length; $j++) { $el = $list->item($j); /* Выводим курсы валют */ if ($el->nodeName == "Name") { $corrency_output[$i]->key = $el->nodeValue . " - "; } elseif ($el->nodeName == "Value") { $corrency_output[$i]->val = $el->nodeValue . "р."; } } } $this->design->assign("corrency_cbrf", $corrency_output); //тест // Отображение $currencies = $this->money->get_currencies(); $currency = $this->money->get_currency(); $this->design->assign('currency', $currency); $this->design->assign('currencies', $currencies); return $this->design->fetch('currency.tpl'); }
<?php $dom = new domDocument(); $data = file_get_contents(dirname(__FILE__) . "/thedata.xml"); $dom->loadXML($data); // load data from XML string $xp = new DomXPath($dom); // create XPath object $res = $xp->query("//item/title"); // get title element echo $res->item(0)->nodeValue; // get data from 1st entry
/** * add a (list of) datasource(s) to an (array of) rrd file(s) * @param array $file_array - array of rrd files * @param array $ds_array - array of datasouce parameters * @param bool $debug - debug mode * returns mixed - success (bool) or error message (array) */ function api_rrd_datasource_add($file_array, $ds_array, $debug) { require_once(CACTI_BASE_PATH."/lib/rrd.php"); require(CACTI_BASE_PATH . "/include/data_source/data_source_arrays.php"); #print_r($ds_array); $rrd_struc = array(); /* iterate all given rrd files */ foreach($file_array as $file) { /* create a DOM object from an rrdtool dump */ $dom = new domDocument; $dom->loadXML(rrdtool_execute("dump $file", false, RRDTOOL_OUTPUT_STDOUT, $rrd_struc, 'UTIL')); if (!$dom) { $check["err_msg"] = __('Error while parsing the XML of rrdtool dump'); return $check; } /* rrdtool dump depends on rrd file version: * version 0001 => RRDTool 1.0.x * version 0003 => RRDTool 1.2.x, 1.3.x, 1.4.x */ $version = trim($dom->getElementsByTagName('version')->item(0)->nodeValue); /* now start XML processing */ foreach($ds_array as $ds) { /* first, append the <DS> strcuture in the rrd header */ if ($ds['type'] === $data_source_types[DATA_SOURCE_TYPE_COMPUTE]) { append_COMPUTE_DS($dom, $version, $ds['name'], $ds['type'], $ds['cdef']); }else { append_DS($dom, $version, $ds['name'], $ds['type'], $ds['heartbeat'], $ds['min'], $ds['max']); } /* now work on the <DS> structure as part of the <cdp_prep> tree */ append_CDP_Prep_DS($dom, $version); /* add <V>alues to the <database> tree */ append_Value($dom); } if($debug) { echo $dom->saveXML(); }else { /* for rrdtool restore, we need a file, so write the XML to disk */ $xml_file = $file . '.xml'; $rc = $dom->save($xml_file); /* verify, if write was successful */ if ($rc === false) { $check["err_msg"] = __('ERROR while writing XML file: %s', $xml_file); return $check; }else { /* are we allowed to write the rrd file? */ if (is_writable($file)) { /* restore the modified XML to rrd */ rrdtool_execute("restore -f $xml_file $file", false, RRDTOOL_OUTPUT_STDOUT, $rrd_struc, 'UTIL'); /* scratch that XML file to avoid filling up the disk */ unlink($xml_file); cacti_log(__("Added datasource(s) to rrd file: %s", $file), false, 'UTIL'); }else { $check["err_msg"] = __('ERROR: RRD file %s not writeable', $file); return $check; } } } } return true; }
/** * protected function replaceValue * Called with the tag : * <RENDER_VALUE what="[class]:[varName]" /> * eg. : <RENDER_VALUE what="body:beginning" /> */ protected function replaceValue($tag, $dest) { // We only take care of the "what" attribute $what = $tag->getAttribute('what'); $quotes = ''; if ($tag->hasAttribute('quotes')) { $quotes = $tag->getAttribute('quotes'); } if (trim($what) != '') { $this->debug('We want to replace the value of "' . $what . '"', 3, __LINE__); $content = $this->changeValue($what); $this->separateArgs($content, $class, $element); if ($element == '') { $textContent = trim($this->values[$class]); } else { if ($class == 'i18n') { $value = $this->linker->i18n->get($this->i18nClasses[$_SESSION['rendering']], $element); $value = '<content>' . $quotes . $value . $quotes . '</content>'; $tempNode = new domDocument('1.0', 'UTF-8'); $status = @$tempNode->loadXML($value); if ($status) { $content = $tempNode->firstChild; $this->enterChildren($content, $dest); } else { $this->debug('Error loading XML (' . $element . '", "' . $class . '")', 0, __LINE__); } return true; } elseif ($class == 'constants' && defined(strtoupper($element))) { $textContent = constant(strtoupper($element)); } else { $textContent = trim($this->values[$class][$element]); } } $textContent = $quotes . $textContent . $quotes; if ($textContent != '') { // We take the text as an xml part, even if it is not $value = '<content>' . $textContent . '</content>'; $tempNode = new domDocument('1.0', 'UTF-8'); $status = @$tempNode->loadXML($value); if ($status) { $content = $tempNode->firstChild; $this->enterChildren($content, $dest); } else { $this->debug('Error loading XML (' . $element . '", "' . $class . '")', 0, __LINE__); } return true; } else { // Error : [varName] does not exist in [class] $this->debug('We didn\'t find any value "' . $element . '" in the "' . $class . '" class', 1, __LINE__); return false; } } // Error : There was no "what" attribute $this->debug('We didn\'t find any "what" attribute for a ' . __FUNCTION__, 0, __LINE__); return false; }
public function get_datas() { //on commence par récupérer l'identifiant retourné par le sélecteur... if ($this->parameters['selector'] != "") { for ($i = 0; $i < count($this->selectors); $i++) { if ($this->selectors[$i]['name'] == $this->parameters['selector']) { $selector = new $this->parameters['selector']($this->selectors[$i]['id']); break; } } @ini_set("zend.ze1_compatibility_mode", "0"); $information = array(); $loaded = false; $aCurl = new Curl(); $aCurl->timeout = $this->parameters['timeout']; $url = $selector->get_value(); if (is_array($url)) { $url = $url[0]; } $content = $aCurl->get($url); $flux = $content->body; if ($flux && $content->headers['Status-Code'] == 200) { $rss = new domDocument(); $loaded = $rss->loadXML($flux); } if ($loaded) { //les infos sur le flux... //Flux RSS if ($rss->getElementsByTagName("channel")->length > 0) { $channel = $rss->getElementsByTagName("channel")->item(0); $elements = array('title', 'description', 'generator', 'link'); $informations = $this->get_informations($channel, $elements, 1); //on va lire les infos des items... $informations['items'] = array(); $items = $rss->getElementsByTagName("item"); $elements = array('title', 'description', 'link', 'guid', 'date', 'creator', 'subject', 'format', 'language'); for ($i = 0; $i < $items->length; $i++) { if ($this->parameters['nb_max_elements'] == 0 || $i < $this->parameters['nb_max_elements']) { $informations['items'][] = $this->get_informations($items->item($i), $elements, false); } } //Flux ATOM } elseif ($rss->getElementsByTagName("feed")->length > 0) { $feed = $rss->getElementsByTagName("feed")->item(0); $atom_elements = array('title', 'subtitle', 'link', 'updated', 'author', 'id'); $informations = $this->get_atom_informations($feed, $atom_elements, 1); //on va lire les infos des entries... $informations['items'] = array(); $entries = $rss->getElementsByTagName("entry"); $atom_elements = array('title', 'link', 'id', 'author', 'issued', 'modified', 'published', 'content'); for ($i = 0; $i < $entries->length; $i++) { if ($this->parameters['nb_max_elements'] == 0 || $i < $this->parameters['nb_max_elements']) { $informations['items'][] = $this->get_atom_informations($entries->item($i), $atom_elements, false); } } } } @ini_set("zend.ze1_compatibility_mode", "1"); return $informations; } return false; }
/** * Runs a URL through Readability and hands back the stripped content * * @since 1.7 * @see http://www.keyvan.net/2010/08/php-readability/ * @param $url */ public static function readability_object($url) { set_time_limit(0); $url = pf_de_https($url); $url = str_replace('&', '&', $url); //print_r($url); print_r(' - Readability<br />'); // change from Boone - use wp_remote_get() instead of file_get_contents() $request = wp_remote_get($url, array('timeout' => '30')); if (is_wp_error($request)) { $content = 'error-secured'; //print_r($request); die(); return $content; } if (!empty($request['body'])) { $html = $request['body']; } else { $content = false; return $content; } //check if tidy exists to clean up the input. if (function_exists('tidy_parse_string')) { $tidy = tidy_parse_string($html, array(), 'UTF8'); $tidy->cleanRepair(); $html = $tidy->value; } // give it to Readability $readability = new Readability($html, $url); // print debug output? // useful to compare against Arc90's original JS version - // simply click the bookmarklet with FireBug's // console window open $readability->debug = false; // convert links to footnotes? $readability->convertLinksToFootnotes = false; // process it $result = $readability->init(); if ($result) { $content = $readability->getContent()->innerHTML; //$content = $contentOut->innerHTML; //if we've got tidy, let's use it. if (function_exists('tidy_parse_string')) { $tidy = tidy_parse_string($content, array('indent' => true, 'show-body-only' => true), 'UTF8'); $tidy->cleanRepair(); $content = $tidy->value; } $content = balanceTags($content, true); $content = ent2ncr($content); $content = convert_chars($content); $domRotated = 0; $dom = new domDocument('1.0', 'utf-8'); $dom->preserveWhiteSpace = true; $dom->substituteEntities = true; $dom->resolveExternals = true; $dom->loadXML('<fullContent>' . $content . '</fullContent>'); $images = $dom->getElementsByTagName('img'); foreach ($images as $image) { $img = $image->getAttribute('src'); if (strpos($img, '/') === 0 || strpos($img, 'http') != 0) { $urlArray = parse_url($url); if (strpos($img, 'http') != 0) { $urlBase = 'http://' . $urlArray['host'] . '/'; } else { $urlBase = 'http://' . $urlArray['host']; } if (!is_wp_error(wp_remote_head($urlBase . $img))) { $image->setAttribute('src', $urlBase . $img); $domRotated++; } elseif (!is_wp_error(wp_remote_head($url . $img))) { $image->setAttribute('src', $url . $img); $domRotated++; } else { $image->parentNode->removeChild($image); $domRotated++; } } } if ($domRotated > 0) { $content = $dom->saveXML(); $rel = '(<\\?xml version="1\\.0" encoding="utf-8"\\?>)'; $content = preg_replace("/" . $rel . "/is", ' ', $content); $rel = '(<\\?xml version="1\\.0"\\?>)'; $content = preg_replace("/" . $rel . "/is", ' ', $content); } if (120 > strlen($content)) { $content = false; } # $content = stripslashes($content); # print_r($content); # var_dump($content); die(); // this will also output doctype and comments at top level # $content = ""; # foreach($dom->childNodes as $node){ # $content .= $dom->saveXML($node)."\n"; # } } else { # If Readability can't get the content, send back a FALSE to loop with. $content = false; # and let's throw up an error via AJAX as well, so we know what's going on. //print_r($url . ' fails Readability.<br />'); } if ($content != false) { $contentObj = new pf_htmlchecker($content); $content = $contentObj->closetags($content); } return $content; }
function save_db($root, $saveXml) { $dom = new domDocument(); $dom->loadXML($saveXml->asXML()); $dom->save($root . "db/fitzroydb.xml"); }
protected function get_items_datas($link) { if ($link) { $datas = array(); @ini_set("zend.ze1_compatibility_mode", "0"); $informations = array(); $loaded = false; $aCurl = new Curl(); $aCurl->timeout = 2; $content = $aCurl->get($link); $flux = $content->body; if ($flux && $content->headers['Status-Code'] == 200) { $rss = new domDocument(); $old_errors_value = false; if (libxml_use_internal_errors(true)) { $old_errors_value = true; } $loaded = $rss->loadXML($flux); if (!count(libxml_get_errors())) { if ($loaded) { //les infos sur le flux... //Flux RSS $sxe = new SimpleXMLElement($flux); $ns = $sxe->getNamespaces(true); $informations['items'] = array(); if ($rss->getElementsByTagName("channel")->length > 0) { $channel = $rss->getElementsByTagName("channel")->item(0); $elements = array('url'); $informations = $this->get_informations($channel, $elements, 1); //on va lire les infos des items... $rss_items = $rss->getElementsByTagName("item"); $elements = array('title', 'description', 'link', 'pubDate', 'category', 'content'); $count = 0; for ($i = 0; $i < $rss_items->length; $i++) { if ($this->parameters['nb_max_elements'] == 0 || $i < $this->parameters['nb_max_elements']) { $informations['items'][$count] = $this->get_informations($rss_items->item($i), $elements, false); if ($ns["dc"]) { $namespace_dc_date = $rss->getElementsByTagNameNS($ns["dc"], 'date')->item($i)->nodeValue; if ($namespace_dc_date) { $informations['items'][$count]['pubDate'] = str_replace(array("T", "Z"), " ", $namespace_dc_date); } $namespace_dc_subject = $rss->getElementsByTagNameNS($ns["dc"], 'subject')->item($i)->nodeValue; if ($namespace_dc_subject) { $informations['items'][$count]['subject'] = $namespace_dc_subject; } } $count++; } } //Flux ATOM } elseif ($rss->getElementsByTagName("feed")->length > 0) { $feed = $rss->getElementsByTagName("feed")->item(0); $atom_elements = array('url'); $informations = $this->get_atom_informations($feed, $atom_elements, 1); //on va lire les infos des entries... $informations['items'] = array(); $entries = $rss->getElementsByTagName("entry"); $atom_elements = array('title', 'link', 'published', 'content'); for ($i = 0; $i < $entries->length; $i++) { if ($this->parameters['nb_max_elements'] == 0 || $i < $this->parameters['nb_max_elements']) { $informations['items'][] = $this->get_atom_informations($entries->item($i), $atom_elements, false); } } } foreach ($informations['items'] as $rss_item) { $data = array(); $data["type"] = "rss"; $data["title"] = $rss_item["title"]; $data["summary"] = $rss_item["description"]; $data["content"] = $rss_item["content"]; $data["url"] = $rss_item["link"]; if ($rss_item["pubDate"]) { $data["publication_date"] = date('Y-m-d h:i:s', strtotime($rss_item["pubDate"])); } else { $data["publication_date"] = ""; } $data["logo_url"] = $informations["url"]; $data["descriptors"] = ""; if (is_array($rss_item["category"])) { $data["tags"] = array_map("strip_tags", $rss_item["category"]); } else { $data["tags"] = strip_tags($rss_item["category"]); } $datas[] = $data; } } } else { libxml_clear_errors(); } } libxml_use_internal_errors($old_errors_value); @ini_set("zend.ze1_compatibility_mode", "1"); return $datas; } else { return false; } }
$resultQuery = Dp::getDpById($PatternID); $anXMLString = '<?xml version="1.0" encoding="UTF-8"?> <Patern> <GENERAL> </GENERAL> <PROBLEM> </PROBLEM> <SET_OF_SOLUTIONS> </SET_OF_SOLUTIONS> <SET_OF_RELATED_PATTERNS> </SET_OF_RELATED_PATTERNS> <PATTERN_IDENTIFICATION> </PATTERN_IDENTIFICATION> </Patern>'; $doc = new domDocument(); $doc->loadXML($anXMLString); $key = key($resultQuery); $val = current($resultQuery); $nbrValues = count($resultQuery); while (list($key, $val) = each($resultQuery)) { if (!is_array($val)) { switch ($key) { case $key == 'pattern_name': $newnode = $doc->createElement($key, $val); $doc->appendChild($newnode); $add = $doc->getElementsByTagName('GENERAL')->item(0); $add->appendChild($newnode); break; case $key == 'pattern_abstract': $newnode = $doc->createElement($key, $val); $doc->appendChild($newnode);
<?php $xslt = new XSLTProcessor(); // Chargement du fichier XML $xmlDoc = new domDocument(); include 'get.inc'; $xmlDoc->loadXML('<?xml version="1.0" encoding="UTF-8" ?>' . getNodeAsXml($_GET['nodeId'])); // Chargement du fichier XSL $xsl = new domDocument(); $xsl->load('xmlNodeToJson.xslt'); // Import de la feuille XSL $xslt->importStylesheet($xsl); // Transformation et affichage du résultat echo $xslt->transformToXml($xmlDoc);
function PrzetworzXML($akcja, $xml_file) { $dom = new domDocument(); $dom->loadXML($xml_file); $xml = simplexml_import_dom($dom); if (isset($xml->Blad)) { $numer = $_POST['numer']; $przyczyna = $xml->Blad; echo 'Błąd ogólny: ' . $przyczyna; } if ($akcja == "wyslij_sms") { if (isset($xml->Odbiorcy->Skolejkowane)) { foreach ($xml->Odbiorcy->Skolejkowane->SMS as $sms) { echo ' Zapis wysłanych do bazy - smsid: ' . xml_attribute($sms, 'id') . '; numer: ' . xml_attribute($sms, 'numer') . '; godzina_skolejkowania: ' . xml_attribute($sms, 'godzina_skolejkowania'); } } if (isset($xml->Odbiorcy->Niewyslane)) { foreach ($xml->Odbiorcy->Niewyslane->SMS as $sms) { echo ' Zapis niewysłanych do bazy - smsid: ' . xml_attribute($sms, 'id') . '; numer: ' . xml_attribute($sms, 'numer') . '; przyczyna: ' . xml_attribute($sms, 'przyczyna'); } } } if ($akcja == "sprawdz_sms") { if (isset($xml->SMS)) { foreach ($xml->SMS as $sms) { echo ' Sprawdzanie statusów - smsid: ' . xml_attribute($sms, 'id') . '; numer: ' . xml_attribute($sms, 'numer') . '; stan: ' . xml_attribute($sms, 'stan') . '; przyczyna: ' . xml_attribute($sms, 'przyczyna'); } } } if ($akcja == "ilosc_sms") { if (isset($xml->SMS)) { foreach ($xml->SMS as $sms) { echo ' Sprawdzanie limitów - typ: ' . xml_attribute($sms, 'typ') . '; limit: ' . $sms; } } } if ($akcja == "sprawdz_odpowiedzi") { if (isset($xml->SMS)) { foreach ($xml->SMS as $sms) { echo ' Wiadomość przychodząca - id: ' . xml_attribute($sms, 'id') . '; numer: ' . xml_attribute($sms, 'numer') . '; data: ' . xml_attribute($sms, 'data') . '; tresc: ' . xml_attribute($sms, 'tresc') . '; na numer: ' . xml_attribute($sms, 'na_numer'); } } if (isset($xml->MMS)) { foreach ($xml->MMS as $mms) { echo ' Wiadomość MMS - id: ' . xml_attribute($mms, 'id') . '; numer: ' . xml_attribute($mms, 'numer') . '; data: ' . xml_attribute($mms, 'data') . '; temat: ' . xml_attribute($mms, 'temat'); if (isset($xml->MMS->Zalacznik)) { foreach ($xml->MMS->Zalacznik as $zalacznik) { echo ' Załącznik - id: ' . xml_attribute($zalacznik, 'id') . '; nazwa: ' . xml_attribute($zalacznik, 'nazwa') . '; contenttype: ' . xml_attribute($zalacznik, 'contenttype') . '; zawartość: ' . $zalacznik; } } } } } if ($akcja == "pliki") { if (isset($xml->Plik)) { foreach ($xml->Plik as $plik) { echo ' Plik - id: ' . xml_attribute($plik, 'id') . '; nazwa: ' . $plik->Nazwa . '; rozmiar: ' . $plik->Rozmiar . '; typ: ' . $plik->Typ . '; data: ' . $plik->Data; } } } if ($akcja == "premium_api") { if (isset($xml->SMS) and $xml->SMS == "OK") { echo ' Odpowiedź wysłana - id: ' . xml_attribute($xml->SMS, 'id'); } elseif (isset($xml->SMS)) { foreach ($xml->SMS as $sms) { echo ' Wiadomość: ' . xml_attribute($sms, 'id') . '; na numer: ' . xml_attribute($sms, 'na_numer') . '; z numeru: ' . xml_attribute($sms, 'z_numeru') . '; data: ' . xml_attribute($sms, 'data') . '; limit: ' . xml_attribute($sms, 'limit') . '; tekst: ' . $sms; } } } if ($akcja == "usun_zaplanowane") { if (isset($xml->ZAPLANOWANE)) { foreach ($xml->ZAPLANOWANE as $zaplanowane) { if ($zaplanowane == "OK") { echo ' Usunięto sms - smsid:' . xml_attribute($zaplanowane, 'smsid'); } if ($zaplanowane == "ERR") { echo ' Nie znaleziono wiadomości - smsid:' . xml_attribute($zaplanowane, 'smsid'); } } } } if ($akcja == "pobierz_mms") { if (isset($xml->MMS)) { foreach ($xml->MMS as $mms) { echo ' Wiadomość MMS - id: ' . xml_attribute($mms, 'id') . '; numer: ' . xml_attribute($mms, 'numer') . '; data: ' . xml_attribute($mms, 'data'); if (isset($mms->Zalacznik)) { foreach ($mms->Zalacznik as $zalacznik) { echo ' Załącznik - id: ' . xml_attribute($zalacznik, 'id') . '; nazwa: ' . xml_attribute($zalacznik, 'nazwa') . '; contenttype: ' . xml_attribute($zalacznik, 'contenttype') . '; zawartość: ' . $zalacznik; } } } } } if ($akcja == "nazwa_nadawcy") { if (isset($xml->NADAWCA)) { foreach ($xml->NADAWCA as $nadawca) { echo ' Nadawca - nazwa: ' . xml_attribute($nadawca, 'nazwa') . '; status: ' . $nadawca; } } } if ($akcja == "hlr") { if (isset($xml->NUMER)) { echo ' Numer: ' . xml_attribute($xml->NUMER, 'numer') . '; status: ' . $xml->NUMER->status . '; imsi: ' . $xml->NUMER->imsi . '; sieć macierzysta: ' . $xml->NUMER->siec_macierzysta . '; przenoszony: ' . $xml->NUMER->przenoszony . '; sieć obecna: ' . $xml->NUMER->siec_obecna; } } if ($akcja == "kontakty") { if (isset($xml->GRUPA->KONTAKT)) { if (isset($xml->GRUPA->NAZWA)) { echo ' Nazwa grupy: ' . $xml->GRUPA->NAZWA . '; ID grupy: ' . xml_attribute($xml->GRUPA, 'id') . '; liczba kontaktów: ' . xml_attribute($xml->GRUPA, 'ilosc'); } foreach ($xml->GRUPA->KONTAKT as $kontakt) { if (isset($kontakt)) { echo ' ID kontaktu: ' . xml_attribute($kontakt, 'id') . '; Telefon: ' . $kontakt->TELEFON . '; E-mail: ' . $kontakt->EMAIL . '; Firma: ' . $kontakt->FIRMA . '; Imie: ' . $kontakt->IMIE . '; Nazwisko: ' . $kontakt->NAZWISKO; } } } elseif (isset($xml->GRUPA->NAZWA)) { foreach ($xml as $grupy) { if (isset($grupy)) { echo ' Nazwa grupy: ' . $grupy->NAZWA . '; ID grupy: ' . xml_attribute($grupy, 'id') . '; liczba kontaktów: ' . xml_attribute($grupy, 'ilosc'); } } } elseif (isset($xml->GRUPA)) { echo ' ID grupy: ' . xml_attribute($xml->GRUPA, 'id') . '; Stan: ' . $xml->GRUPA; } elseif (isset($xml->KONTAKT)) { echo ' ID kontaktu: ' . xml_attribute($xml->KONTAKT, 'id') . '; Stan: ' . $xml->KONTAKT; } } }
/** * * @get text between tags * @param string $tag The tag name * @param string $html The XML or XHTML string * @param int $strict Whether to use strict mode * @param string $encoding * @return array */ private function getTextBetweenTags($tag, $html, $strict = 0, $encoding = "UTF-8") { global $PAGE, $CFG; if (!isset($CFG->filter_jsxgraph_divid)) { set_config('filter_jsxgraph_divid', 'box'); } if (!isset($CFG->filter_jsxgraph_boardvar)) { set_config('filter_jsxgraph_boardvar', 'board'); } if (!isset($CFG->filter_jsxgraph_width)) { set_config('filter_jsxgraph_width', '500'); } if (!isset($CFG->filter_jsxgraph_height)) { set_config('filter_jsxgraph_height', '400'); } // a new dom object $dom = new domDocument(); $dom->formatOutput = true; // load the html into the object if ($strict == 1) { $dom->loadXML($html); } else { libxml_use_internal_errors(true); $htmlutf8 = mb_convert_encoding($html, 'HTML-ENTITIES', $encoding); $dom->loadHTML($htmlutf8); libxml_use_internal_errors(false); } // discard white space $dom->preserveWhiteSpace = false; $dom->strictErrorChecking = false; $dom->recover = true; // the tag by its tag name $content = $dom->getElementsByTagname($tag); if (count($content) > 0) { $PAGE->requires->js(new moodle_url($CFG->wwwroot . '/filter/jsxgraph/jsxgraphcore.js')); } // Iterate backwards through the jsxgraph tags $i = $content->length - 1; while ($i > -1) { $item = $content->item($i); // Read attributes $w = $item->getAttribute('width'); if ($w == "") { $w = $CFG->filter_jsxgraph_width; } $h = $item->getAttribute('height'); if ($h == "") { $h = $CFG->filter_jsxgraph_height; } $b = $item->getAttribute('box'); if ($b == "") { $b = $CFG->filter_jsxgraph_divid . $i; } $brd = $item->getAttribute('board'); if ($brd == "") { $brd = $CFG->filter_jsxgraph_boardvar . $i; } /* Create new div element containing JSXGraph */ $out = $dom->createElement('div'); $a = $dom->createAttribute('id'); $a->value = $b; $out->appendChild($a); $a = $dom->createAttribute('class'); $a->value = "jxgbox"; $out->appendChild($a); $a = $dom->createAttribute('style'); $a->value = "width:" . $w . "px; height:" . $h . "px; "; $out->appendChild($a); $t = $dom->createTextNode(""); $out->appendChild($t); $out = $dom->appendChild($out); // Replace <jsxgraph> by <div> $item->parentNode->replaceChild($out, $item); $code = ""; $needGXT = false; $url = $item->getAttribute('file'); if ($url != "") { $code = "var " . $brd . " = JXG.JSXGraph.loadBoardFromFile('" . $b . "', '" . $url . "', 'Geonext');"; $needGXT = true; } else { $url = $item->getAttribute('filestring'); if ($url != "") { $code = "var " . $brd . " = JXG.JSXGraph.loadBoardFromString('" . $b . "', '" . $url . "', 'Geonext');"; $needGXT = true; } else { // Plain JavaScript code $code = $item->nodeValue; } } // Place JavaScript code at the end of the page. $PAGE->requires->js_init_call($code); if ($needGXT) { $PAGE->requires->js(new moodle_url($CFG->wwwroot . '/filter/jsxgraph/GeonextReader.js')); } --$i; } // remove DOCTYPE $dom->removeChild($dom->firstChild); // remove <html><body></body></html> //$dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild); //return $dom->saveXML(); $str = $dom->saveHTML(); $str = str_replace("<body>", "", $str); $str = str_replace("</body>", "", $str); $str = str_replace("<html>", "", $str); $str = str_replace("</html>", "", $str); return $str; }