function file_write() { extract($GLOBALS); $dom = new DomDocument('1.0', 'UTF-8'); $prefs = $dom->appendChild($dom->createElement('prefs')); for ($i = 0; $i < 10; $i++) { $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', $power_company[$i] . '_Denryoku'); $pref->appendChild($dom->createElement('den_per', $Power[$power_company[$i]]["den_per"])); $pref->appendChild($dom->createElement('den_old', $Power[$power_company[$i]]["OLD_DATA"])); $pref->appendChild($dom->createElement('den_now', $Power[$power_company[$i]]["usage"])); $pref->appendChild($dom->createElement('den_updown', $Power[$power_company[$i]]["up_down"])); $pref->appendChild($dom->createElement('den_max', $Power[$power_company[$i]]["capacity"])); $pref->appendChild($dom->createElement('den_yosou', $Power[$power_company[$i]]["yosou"])); $pref->appendChild($dom->createElement('den_date', $Power[$power_company[$i]]["DATE"])); $pref->appendChild($dom->createElement('den_time', $Power[$power_company[$i]]["time"])); $pref->appendChild($dom->createElement('den_alive', $Power[$power_company[$i]]["alive"])); } $weekjp = array('日', '月', '火', '水', '木', '金', '土'); $weekno = date('w'); $week_X = "〔" . $weekjp[$weekno] . "〕"; $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', 'DATE'); $pref->appendChild($dom->createElement('time', date("Y年m月d日") . $week_X . date(" H時i分"))); $pref->appendChild($dom->createElement('time_ampm', date("Y年m月d日") . $week_X . date(" A h:i"))); $pref->appendChild($dom->createElement('time_x', date("Ymd"))); $dom->formatOutput = true; $save_file = "/etc/zabbix/externalscripts/" . $OUT_FILE; $dom->save($save_file); }
function file_write() { extract($GLOBALS); $dom = new DomDocument('1.0', 'UTF-8'); $prefs = $dom->appendChild($dom->createElement('prefs')); $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', 'SunMoon'); $pref->appendChild($dom->createElement('sunrise', sprintf("%05s", $ohakon["sunrise"]))); $pref->appendChild($dom->createElement('sunset', sprintf("%05s", $ohakon["sunset"]))); $pref->appendChild($dom->createElement('sunrise_hm', sprintf("%05s", $ohakon["sunrise_hm"]))); $pref->appendChild($dom->createElement('sunset_hm', sprintf("%05s", $ohakon["sunset_hm"]))); $pref->appendChild($dom->createElement('moonrise', sprintf("%05s", $ohakon["moonrise"]))); $pref->appendChild($dom->createElement('moonset', sprintf("%05s", $ohakon["moonset"]))); $pref->appendChild($dom->createElement('moonrise_hm', sprintf("%05s", $ohakon["moonrise_hm"]))); $pref->appendChild($dom->createElement('moonset_hm', sprintf("%05s", $ohakon["moonset_hm"]))); $pref->appendChild($dom->createElement('moon_age', $ohakon["moon_age"])); $pref->appendChild($dom->createElement('moon_phase', $ohakon["moon_phase"])); $pref->appendChild($dom->createElement('fullmoon_wait', $ohakon["fullmoon_wait"])); $pref->appendChild($dom->createElement('newmoon_wait', $ohakon["newmoon_wait"])); $pref->appendChild($dom->createElement('tide_name', $tide_name)); $weekjp = array('日', '月', '火', '水', '木', '金', '土'); $weekno = date('w'); $week_X = "〔" . $weekjp[$weekno] . "〕"; $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', 'DATE'); $pref->appendChild($dom->createElement('time', date("Y年m月j日") . $week_X . date(" H時i分"))); $pref->appendChild($dom->createElement('time_ampm', date("Y年m月j日") . $week_X . date(" A h:i"))); $dom->formatOutput = true; $save_file = "/etc/zabbix/externalscripts/" . $OUT_FILE; $dom->save($save_file); }
/** * @param $nameRoot - имя корня xml * @param $nameBigElement - имя узла в который записываются данные из массива $data * @param $data - массив с данными выгружеными из таблицы */ function createXml($nameRoot, $nameBigElement, $data) { // создает XML-строку и XML-документ при помощи DOM $dom = new DomDocument($this->version, $this->encode); // добавление корня $root = $dom->appendChild($dom->createElement($nameRoot)); // отбираем названия полей таблицы foreach (array_keys($data[0]) as $k) { if (is_string($k)) { $key[] = $k; } } // формируем элементы с данными foreach ($data as $d) { //добавление элемента $nameBigElement в корень $bigElement = $root->appendChild($dom->createElement($nameBigElement)); foreach ($key as $k) { $element = $bigElement->appendChild($dom->createElement($k)); $element->appendChild($dom->createTextNode($d[$k])); } } // сохраняем результат в файл $dom->save('format/' . $this->nameFile); unset($dom); }
function file_write() { extract($GLOBALS); $dom = new DomDocument('1.0', 'UTF-8'); $prefs = $dom->appendChild($dom->createElement('prefs')); $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', 'FullMoon'); $pref->appendChild($dom->createElement('Date', $FM[0] . "-" . $FM[1] . "-" . $FM[2])); $pref->appendChild($dom->createElement('Time', $FM[3] . ":" . $FM[4] . ":" . $FM[5])); $day = day_diff(date('Y-m-d'), $FM[0] . "-" . $FM[1] . "-" . $FM[2]); if ($day < 0) { $day = "--"; } $pref->appendChild($dom->createElement('Wait', $day)); $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', 'NewMoon'); $pref->appendChild($dom->createElement('Date', $NM[0] . "-" . $NM[1] . "-" . $NM[2])); $pref->appendChild($dom->createElement('Time', $NM[3] . ":" . $NM[4] . ":" . $NM[5])); $day = day_diff(date('Y-m-d'), $NM[0] . "-" . $NM[1] . "-" . $NM[2]); if ($day < 0) { $day = "--"; } $pref->appendChild($dom->createElement('Wait', $day)); $weekjp = array('日', '月', '火', '水', '木', '金', '土'); $weekno = date('w'); $week_X = "〔" . $weekjp[$weekno] . "〕"; $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', 'DATE'); $pref->appendChild($dom->createElement('time', date("Y年m月j日") . $week_X . date(" H時i分"))); $pref->appendChild($dom->createElement('time_ampm', date("Y年m月j日") . $week_X . date(" A h:i"))); $dom->formatOutput = true; $save_file = "/etc/zabbix/externalscripts/F_N_Moon.xml"; $dom->save($save_file); }
function file_write() { extract($GLOBALS); $dom = new DomDocument('1.0', 'UTF-8'); $prefs = $dom->appendChild($dom->createElement('prefs')); $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', 'OpenWeatherMap'); $pref->appendChild($dom->createElement('place', $owm["place"])); $pref->appendChild($dom->createElement('description', $owm["description"])); $pref->appendChild($dom->createElement('clouds_value', $owm["clouds_value"])); $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', 'Wunderground'); $pref->appendChild($dom->createElement('city', $wg["city"])); $pref->appendChild($dom->createElement('weather', $wg["weather"])); $pref->appendChild($dom->createElement('kazamuki2', $wg["kazamuki2"])); $pref->appendChild($dom->createElement('kazamuki_degrees', $wg["kazamuki_degrees"])); $pref->appendChild($dom->createElement('temp_now2', $wg["temp_now2"])); $pref->appendChild($dom->createElement('temp_now_f', $wg["temp_now_f"])); $pref->appendChild($dom->createElement('feelslike', $wg["feelslike"])); $pref->appendChild($dom->createElement('humidity_now2', $wg["humidity_now2"])); $pref->appendChild($dom->createElement('windspeed_now2', $wg["windspeed_now2"])); $pref->appendChild($dom->createElement('pressure_now2', $wg["pressure_now2"])); $pref->appendChild($dom->createElement('discomfort', $wg["fukai"])); $weekjp = array('日', '月', '火', '水', '木', '金', '土'); $weekno = date('w'); $week_X = "〔" . $weekjp[$weekno] . "〕"; $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', 'DATE'); $pref->appendChild($dom->createElement('time', date("Y年m月j日") . $week_X . date(" H時i分"))); $pref->appendChild($dom->createElement('time_ampm', date("Y年m月j日") . $week_X . date(" A h:i"))); $dom->formatOutput = true; $save_file = "/etc/zabbix/externalscripts/" . $OUT_FILE; $dom->save($save_file); }
function create_xml_droits($array_section) { $dom_document = new DomDocument("1.0", "UTF-8"); $dom_document->formatOutput = true; $root = $dom_document->createElement("droits"); $root = $dom_document->appendChild($root); foreach ($array_section as $nom_section => $droits) { $section = $dom_document->createElement("section"); $section->setAttribute("name", $nom_section); $section = $root->appendChild($section); foreach ($droits as $nom_droit => $type_droit) { $droit = $dom_document->createElement("droit"); $droit = $section->appendChild($droit); $nom = $dom_document->createElement("name"); $nom = $droit->appendChild($nom); $textNom = $dom_document->createTextNode($nom_droit); $textNom = $nom->appendChild($textNom); $type = $dom_document->createElement("type"); $type = $droit->appendChild($type); $textType = $dom_document->createTextNode($type_droit); $textType = $type->appendChild($textType); } } $dom_document->save(PATH_ROOT . 'inc/droits.xml'); }
/** * Handle provided directory * * Optionally an existing result file can be provided * * If a valid file could be generated the file name is supposed to be * returned, otherwise return null. * * @param Project $project * @param string $existingResult * * @return string */ public function handle(Project $project, $existingResult = null) { if (!isset($project->analyzers['pdepend'])) { return; } $pdependResultFile = $project->dataDir . '/' . $project->analyzers['pdepend']; $document = new \DomDocument(); $document->load($pdependResultFile); $xPath = new \DomXPath($document); foreach ($xPath->query('//package') as $packageNode) { $packageCommits = 0; foreach ($xPath->query('./class', $packageNode) as $classNode) { $fileNode = $xPath->query('./file', $classNode)->item(0); $file = $fileNode->getAttribute('name'); $classCommits = $this->countGitChangesPerFileRange($project, $file, $classNode->getAttribute('start'), $classNode->getAttribute('end')); $packageCommits += $classCommits; $classNode->setAttribute('commits', $classCommits); foreach ($xPath->query('./method', $classNode) as $methodNode) { $methodCommits = $this->countGitChangesPerFileRange($project, $file, $methodNode->getAttribute('start'), $methodNode->getAttribute('end')); $methodNode->setAttribute('commits', $methodCommits); } } $packageNode->setAttribute('commits', $packageCommits); } $document->save($pdependResultFile); return null; }
function teste() { $xml = new DomDocument("1.0", "UTF-8"); /* $container = $xml->createElement('container', 'tkjasdkfjal'); $container = $xml->appendChild($container); $sale = $xml->createElement('sale'); $sale = $container->appendChild($sale); $item = $xml->createElement('item', 'Television'); $item = $sale->appendChild($item); $price = $xml->createElement('price', '$100'); $price = $sale->appendChild($price); */ $cadastro = $xml->createElement('Cadastro'); $cadastro = $xml->appendChild($cadastro); $pessoa = $xml->createElement('Pessoa'); $pessoa = $cadastro->appendChild($pessoa); $nome = $xml->createElement('nome', 'Rodrigo'); $pessoa->appendChild($nome); $situacao = $xml->createElement('situacao', 'fudido'); $pessoa->appendChild($situacao); $xml->FormatOutput = true; $string_value = $xml->saveXML(); $xml->save('xml/teste.xml'); echo 'xml criado, chupa mundo'; exit; //$xml = Xml::build('<example>text</example>', array('app/teste.xml')); //exit; }
public static function generate() { // Там еще в сайтмепе есть приоритетность. Для главной ставим самую высокую, для всех категорий чуть ниже и последняя приоритетность для постов //Создает XML-строку и XML-документ при помощи DOM $dom = new DomDocument('1.0'); //добавление корня - <books> $urlset = $dom->appendChild($dom->createElement('urlset')); $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9'); // Главная страница $url = $urlset->appendChild($dom->createElement('url')); $loc = $url->appendChild($dom->createElement('loc')); $loc->appendChild($dom->createTextNode("http://" . $_SERVER['SERVER_NAME'])); $priority = $url->appendChild($dom->createElement('priority')); $priority->appendChild($dom->createTextNode('1.0')); // Категории фото $categoryPhoto = CategoryPhoto::find()->all(); foreach ($categoryPhoto as $category) { $url = $urlset->appendChild($dom->createElement('url')); $loc = $url->appendChild($dom->createElement('loc')); $loc->appendChild($dom->createTextNode("http://" . $_SERVER['SERVER_NAME'] . "/category/photo/" . $category->url)); $priority = $url->appendChild($dom->createElement('priority')); $priority->appendChild($dom->createTextNode('0.7')); } // Категории видео $categoryVideo = Category::find()->all(); foreach ($categoryVideo as $category) { $url = $urlset->appendChild($dom->createElement('url')); $loc = $url->appendChild($dom->createElement('loc')); $loc->appendChild($dom->createTextNode("http://" . $_SERVER['SERVER_NAME'] . "/category/video/" . $category->url)); $priority = $url->appendChild($dom->createElement('priority')); $priority->appendChild($dom->createTextNode('0.7')); } // Страницы фото $photoCatalog = PhotoCatalog::find()->where('publish = 1')->all(); foreach ($photoCatalog as $photo) { $url = $urlset->appendChild($dom->createElement('url')); $loc = $url->appendChild($dom->createElement('loc')); $loc->appendChild($dom->createTextNode("http://" . $_SERVER['SERVER_NAME'] . "/photo/" . $photo->category->url . "/" . $photo->url)); $priority = $url->appendChild($dom->createElement('priority')); $priority->appendChild($dom->createTextNode('0.5')); } // Страницы видео $videos = Video::find()->where('publish = 1')->all(); foreach ($videos as $video) { $url = $urlset->appendChild($dom->createElement('url')); $loc = $url->appendChild($dom->createElement('loc')); $loc->appendChild($dom->createTextNode("http://" . $_SERVER['SERVER_NAME'] . "/video/" . $video->category->url . "/" . $video->url)); $priority = $url->appendChild($dom->createElement('priority')); $priority->appendChild($dom->createTextNode('0.5')); } //генерация xml $dom->formatOutput = true; // установка атрибута formatOutput // domDocument в значение true // save XML as string or file //$test1 = $dom->saveXML(); // передача строки в test1 $dom->save('../web/sitemap.xml'); // сохранение файла }
/** * Save current DomDocument to the filesystem * * @throws t41_Backend_Exception */ protected function _saveRessource() { if (!$this->_ressource instanceof \DOMDocument) { throw new Exception("BACKEND_RESSOURCE_NO_RESSOURCE"); } $this->_ressource->formatOutput = true; $this->_ressource->save($this->_path . $this->_file); }
function setAttribute($xmlfile, $attrName, $attrVal) { $doc = new DomDocument(); $doc->load($xmlfile); $elem = $doc->documentElement; $elem->setAttribute($attrName, $attrVal); // save xml file $doc->formatOutput = true; $doc->save($xmlfile); }
function islem() { if (isset($_POST['insert'])) { header("Content-Type: text/html; charset=utf8"); $get = mb_convert_case($_POST['c_name'], MB_CASE_TITLE, "UTF-8"); $xml = simplexml_load_file("kitapdb.xml"); foreach ($xml->KITAP as $KITAP) { if ($get == $KITAP->K_ADI) { echo '<div class="uyari">AYNI KİTABI TEKRAR ALAMAZSINIZ !</div>'; echo '<script>setTimeout(function(){location.href="index.php"} , 3000); </script>'; return false; } } header("Content-Type: text/html; charset=utf8"); $xml = new DomDocument("1.0", "UTF-8"); $xml->load('kitapdb.xml'); $k = mb_convert_case($_POST['c_name'], MB_CASE_TITLE, "UTF-8"); $y = mb_convert_case($_POST['yazar'], MB_CASE_TITLE, "UTF-8"); $s = $_POST['sayfa_sayisi']; $o = mb_convert_case($_POST['ogrenci'], MB_CASE_TITLE, "UTF-8"); $o2 = mb_convert_case($_POST['ogrenci2'], MB_CASE_TITLE, "UTF-8"); $rootTag = $xml->getElementsByTagName('liste')->item(0); $infoTag = $xml->createElement("KITAP"); $nameTag = $xml->createElement("K_ADI", $k); $YazarTag = $xml->createElement("YAZAR", $y); $SayiTag = $xml->createElement("S_SAYISI", $s); $OgrenciTag = $xml->createElement("OGRENCI", $o); $Ogrenci2Tag = $xml->createElement("OGRENCI2", $o2); $durum = $xml->createElement("DURUM", 1); $infoTag->appendChild($nameTag); $infoTag->appendChild($YazarTag); $infoTag->appendChild($SayiTag); $infoTag->appendChild($OgrenciTag); $infoTag->appendChild($Ogrenci2Tag); $infoTag->appendChild($durum); $rootTag->appendChild($infoTag); $xml->save('kitapdb.xml'); echo '<script>setTimeout(function(){location.href="index.php"} , 5000); </script>'; //MAIL GONDER echo '<center><h2>Kitap alma işlemi başarıyla gerçekleşti.<br>Anasayfaya yönlendiriliyorsunuz...<br> <img src="loading.gif" width="32" alt=""></h2></center>'; exit; } }
function file_write() { extract($GLOBALS); $dom = new DomDocument('1.0', 'UTF-8'); $prefs = $dom->appendChild($dom->createElement('prefs')); $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', 'WinOS'); $pref->appendChild($dom->createElement('Vista', sprintf("%d", $Vista))); $pref->appendChild($dom->createElement('Win7', sprintf("%d", $Win7))); $weekjp = array('日', '月', '火', '水', '木', '金', '土'); $weekno = date('w'); $week_X = "〔" . $weekjp[$weekno] . "〕"; $pref = $prefs->appendChild($dom->createElement('pref')); $pref->setAttribute('code', 'DATE'); $pref->appendChild($dom->createElement('time', date("Y年m月j日") . $week_X . date(" H時i分"))); $pref->appendChild($dom->createElement('time_ampm', date("Y年m月j日") . $week_X . date(" A h:i"))); $dom->formatOutput = true; $save_file = "/etc/zabbix/externalscripts/" . $OUT_FILE; $dom->save($save_file); }
function crear() { $xml = new DomDocument('1.0', 'UTF-8'); $biblioteca = $xml->createElement('biblioteca'); $biblioteca = $xml->appendChild($biblioteca); $libro = $xml->createElement('libro'); $libro = $biblioteca->appendChild($libro); $autor = $xml->createElement('autor', 'Paulo Coelho'); $autor = $libro->appendChild($autor); $titulo = $xml->createElement('titulo', 'El Alquimista'); $titulo = $libro->appendChild($titulo); $anio = $xml->createElement('anio', '1988'); $anio = $libro->appendChild($anio); $editorial = $xml->createElement('editorial', 'Maxico D.F. - Editorial Grijalbo'); $editorial = $libro->appendChild($editorial); $xml->formatOutput = true; $el_xml = $xml->saveXML(); $xml->save('libros.xml'); //Mostramos el XML puro echo "<p><b>El XML ha sido creado.... Mostrando en texto plano:</b></p>" . htmlentities($el_xml) . "<br/><hr>"; }
function addComment($CommentFile, $date_value, $author_value, $subject_value, $msg_value, $ip) { $xml = new DomDocument('1.0', 'utf-8'); if (file_exists($CommentFile)) { $xml->load($CommentFile); $root = $xml->firstChild; } else { $root = $xml->appendChild($xml->createElement("comments")); } $comment = $xml->createElement("comment"); $root->appendChild($comment); // Add date attribute $attr_date = $xml->createAttribute("timestamp"); $comment->appendChild($attr_date); $value = $xml->createTextNode($date_value); $attr_date->appendChild($value); // Add author attribute $attr_author = $xml->createAttribute("author"); $comment->appendChild($attr_author); $value = $xml->createTextNode($author_value); $attr_author->appendChild($value); // Add author ip address $attr_ip = $xml->createAttribute("ip"); $comment->appendChild($attr_ip); $value = $xml->createTextNode($ip); $attr_ip->appendChild($value); // add subject child node $subject = $xml->createElement("subject"); $comment->appendChild($subject); $value = $xml->createTextNode($subject_value); $subject->appendChild($value); // add message child node $msg = $xml->createElement("message"); $comment->appendChild($msg); $value = $xml->createTextNode($msg_value); $msg->appendChild($value); $xml->save($CommentFile); return $xml->getElementsByTagName("comment")->length; }
function validando_xml($id, $fecha, $total, $detalle, $cliente, $ruc_ced, $tot_sin_impuestos, $descuento, $iva, $diferencia, $telefono, $factura_num, $direccion_cliente, $orden_numero) { $xml = ' <?xml version="1.0" encoding="UTF-8"?>' . '<factura id="comprobante" version="1.0.0">' . '<infoTributaria>' . '<ambiente>2</ambiente>' . '<tipoEmision>1</tipoEmision>' . '<razonSocial>EMRESA TOTORA SISA Scc</razonSocial>' . '<nombreComercial>TOTORA SISA</nombreComercial>' . '<ruc>1791256115001</ruc>' . '<claveAcceso>0802201501179125611500120013270130149142658602812</claveAcceso>' . '<codDoc>01</codDoc>' . '<estab>001</estab>' . '<ptoEmi>327</ptoEmi>' . '<secuencial>013014914</secuencial>' . '<dirMatriz>San Rafael de la Laguna calle Bolívar y Imbakucha Parque Central, Otavalo,IMBABURA,ECUADOR</dirMatriz>' . '</infoTributaria>' . '<infoFactura>' . '<fechaEmision>' . $fecha . '</fechaEmision>' . '<dirEstablecimiento>San Rafael de la Laguna calle Bolívar y Imbakucha Parque Central, Otavalo,IMBABURA,ECUADOR</dirEstablecimiento>' . '<contribuyenteEspecial>5368</contribuyenteEspecial>' . '<tipoIdentificacionComprador>05</tipoIdentificacionComprador>' . '<razonSocialComprador>' . $cliente . '</razonSocialComprador>' . '<identificacionComprador>' . $ruc_ced . '</identificacionComprador>' . '<totalSinImpuestos>' . $tot_sin_impuestos . '</totalSinImpuestos>' . '<totalDescuento>' . $descuento . '</totalDescuento>' . '<totalConImpuestos>' . '<totalImpuesto>' . '<codigo>2</codigo>' . '<codigoPorcentaje>2</codigoPorcentaje>' . '<baseImponible>' . $total . '</baseImponible>' . '<tarifa>' . $iva . '</tarifa>' . '<valor>' . $diferencia . '</valor>' . '</totalImpuesto>' . '</totalConImpuestos>' . '<propina>0.00</propina>' . '<importeTotal>' . $total . '</importeTotal>' . '<moneda>DOLAR</moneda>' . '</infoFactura>' . '<detalles>' . $detalle . '</detalle>' . '<infoAdicional>' . '<campoAdicional nombre="Teléfono">' . $telefono . '</campoAdicional>' . '<campoAdicional nombre="Página web">https://empresatotorasisa.wordpress.com</campoAdicional>' . '<campoAdicional nombre="rucFirmante">1791256115001</campoAdicional>' . '<campoAdicional nombre="Factura">' . $factura_num . '</campoAdicional>' . '<campoAdicional nombre="account">26586028</campoAdicional>' . '<campoAdicional nombre="DireccionComprador">' . $direccion_cliente . '</campoAdicional>' . '<campoAdicional nombre="NoOrdenFactura">' . $orden_numero . '</campoAdicional>' . '</infoAdicional>' . '</factura>'; $acu = str_replace('</', '<', $xml); $acu1 = str_replace('<', '<', $acu); $xml = str_replace('>', '>', $acu1); $dom = new DomDocument('1.0', 'UTF-8'); //add root $root = $dom->appendChild($dom->createElement('autorizacion')); //add NodeA element to Root $nodeA = $dom->createElement('estado', 'AUTORIZADO'); $nodeB = $dom->createElement('numeroAutorizacion', '0902201514132517912561150012784234238'); $nodeC = $dom->createElement('fechaAutorizacion', $fecha); $nodeD = $dom->createElement('ambiente', 'PRODUCCIÓN_DESARROLLO'); $nodeE = $dom->createElement('comprobante', $xml); $root->appendChild($nodeA); $root->appendChild($nodeB); $root->appendChild($nodeC); $root->appendChild($nodeD); $root->appendChild($nodeE); $dom->formatOutput = true; // set the formatOutput attribute of domDocument to true // save XML as string or file $test1 = $dom->saveXML(); // put string in test1 $nom_archivo = 'xml/FAC_ELECTRONICA' . $id . '.xml'; $dom->save($nom_archivo); // save as file $zip = new ZipArchive(); $filename = "zip_rar/factura_electronica" . $id . ".zip"; if ($zip->open($filename, ZipArchive::CREATE) !== TRUE) { exit("cannot open <{$filename}>\n"); } $nom_arch = 'FAC_ELE' . $id . '.xml'; $zip->addFromString($nom_arch . time(), "#1 Esto es una cadena de prueba añadida como testfilephp.txt.\n"); $zip->close(); }
public function ChargerFonctions($xmlfile, Doctrine_Connection $conn = null) { /* Tous les objets vont etre recharger sur le projet courant. * Du coup on récupère l'id et le ref du projet */ $project_id = $this->getProjectId(); $project_ref = $this->getRefId(); if ($conn == null) { $conn = Doctrine_Manager::connection(); } $dom = new DomDocument(); if ($xmlfile != null) { $dom->loadXML($xmlfile); $dom->save('projet.xml'); /* A utiliser en cas de deboguage pour visualiser le contenu du fichier */ //recherche de l'element racine <projets> if ($dom->documentElement) { $projets = $dom->documentElement; //rechargement des données du projet //si le projet a été trouvé if ($projets->getElementsByTagName("info")->item(0)) { MyFunction::rechargerProjet($projets->getElementsByTagName("info")->item(0), true, $conn); //Création des tables temporaires pour opérations d'insert - delete //Table temporaire des fonctions Doctrine_Core::getTable('ScriptEiFunction')->insertTmpData($projets, $project_id, $project_ref, $conn); //Table temporaire des dossiers de fonctions (EiView) Doctrine_Core::getTable('ScriptEiView')->insertTmpData($projets, $project_id, $project_ref, $conn); //Table temporaire des scripts Doctrine_Core::getTable('ScriptEiScript')->insertTmpData($projets, $project_id, $project_ref, $conn); //Table temporaire des relations script-profil Doctrine_Core::getTable('ScriptEiScriptVersion')->insertTmpData($projets, $project_id, $project_ref, $conn); //Table temporaire des notices Doctrine_Core::getTable('ScriptEiNotice')->insertTmpData($projets, $project_id, $project_ref, $conn); //Table temporaire des profils de notice Doctrine_Core::getTable('ScriptEiNoticeProfil')->insertTmpData($projets, $project_id, $project_ref, $conn); //Table temporaire des versions de notice Doctrine_Core::getTable('ScriptEiVersionNotice')->insertTmpData($projets, $project_id, $project_ref, $conn); //Rechargement des relations version_notice-profil du projet Doctrine_Core::getTable('EiNoticeProfil')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des versions de notice d'un projet Doctrine_Core::getTable('EiVersionNotice')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des notice d'un projet //$this->getNotices()->delete($conn); Doctrine_Core::getTable('EiNotice')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des liaisons utilisateurs-tickets $this->getUserTickets()->delete($conn); //Doctrine_Core::getTable('EiUserTicket')->deleteUserTicketForProject($project_id, $project_ref , $conn); Doctrine_Core::getTable('EiUserTicket')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des paramètres de profil //$this->getProjectProfileParams()->delete($conn); Doctrine_Core::getTable('EiProfileParam')->deleteProjectProfileParams($project_id, $project_ref, $conn); Doctrine_Core::getTable('EiProfileParam')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des paramètres d'une fonction Doctrine_Core::getTable('EiFunctionHasParam')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des liaisons script-profil des fonctions d'un projet Doctrine_Core::getTable('EiScriptVersion')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des scripts de fonction Doctrine_Core::getTable('EiScript')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des fonctions (KalFunction pour ne pas créer d'ambiguité avec EiFonction) Doctrine_Core::getTable('KalFunction')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des commandes de fonction d'un projet Doctrine_Core::getTable('EiFunctionHasCommande')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des vues du projet //Doctrine_Core::getTable('EiView')->deleteProjectViews($project_id, $project_ref , $conn); Doctrine_Core::getTable('EiView')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des profils //Doctrine_Core::getTable('EiProfil')->deleteProjectProfiles($project_id, $project_ref , $conn ); Doctrine_Core::getTable('EiProfil')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des tickets Doctrine_Core::getTable('EiTicket')->deleteProjectTickets($project_id, $project_ref, $conn); Doctrine_Core::getTable('EiTicket')->reload($projets, $project_id, $project_ref, $conn); //récupération des noeuds ouverts pour les garder ouverts. $nodes = $this->getAllProjectNodes(); $openNodes = array(); foreach ($nodes as $i => $n) { $opened = $n->getEiTreeOpenedByUsers(); if ($opened->count() > 0) { $openNodes[$n->getId()] = $opened; } } //Doctrine_Core::getTable('EiTree')->deleteProjectNodes($project_id, $project_ref ,$conn); //Rechargement de l'arbre Doctrine_Core::getTable('EiTree')->reload($projets, $project_id, $project_ref, $conn, $openNodes); //Rechargement des langues du projet Doctrine_Core::getTable('EiProjectLang')->deleteProjectLangs($project_id, $project_ref, $conn); Doctrine_Core::getTable('EiProjectLang')->reload($projets, $project_id, $project_ref, $conn); //Rechargement des paramètres globaux du projet Doctrine_Core::getTable('EiProjectParam')->deleteProjectParams($project_id, $project_ref, $conn); Doctrine_Core::getTable('EiProjectParam')->reload($projets, $project_id, $project_ref, $conn); //Suppression des fonctions inactives Doctrine_Core::getTable('KalFunction')->deleteInactiveFunctions($this, $conn); //Création des status par défaut du projet $this->createDefaultStates($conn); } } else { $d = date('Y-m-d H:i:s'); $this->setObsolete(true); $this->setCheckedAt($d); $this->save(); } } return null; }
function moderate($action) { $page = realpath('.') . '/' . $_POST["page"] . '.xml'; $comment_id = $_POST["comment"]; if (is_file($page)) { $xml = new DomDocument('1.0', 'utf-8'); if ($xml->load($page, LIBXML_NOBLANKS)) { $xpath = new DOMXPath($xml); $result = $xpath->query("//comments/dom-element/descendant::comment[@id='{$comment_id}']"); if ($result->length === 1) { $node = $result->item(0); switch ($action) { case "ok": $node->setAttribute("moderate", "4"); break; case "trash": $node->setAttribute("moderate", "2"); break; case "spam": $node->setAttribute("moderate", "3"); addToSpamer($node->getAttribute("ip")); break; } $xml->save($page); } } } echo json_encode(array('status' => 0)); }
/** * Deinitializes the writer * * @return void */ public function deinitWriter() { if (is_null($this->dom)) { throw new ezcTranslationWriterNotInitializedException(); } $filename = $this->buildTranslationFileName($this->writeLocale); $this->dom->save($filename); }
function addImageMetadata_datastream($obj_pid = null, $obj_height = null, $obj_width = null, $obj_jp2URL = null, $obj_rft_id = null, $obj_sourceURL = null, &$obj_dom = null, &$obj_rootElement = null) { if ($obj_dom == null && $this->dom != null) { $obj_pid = $this->pid; $obj_dom =& $this->dom; $obj_rootElement =& $this->rootElement; $obj_height = $this->height; $obj_width = $this->width; $obj_jp2URL = $this->jp2URL; $obj_rft_id = $this->rft_id; $obj_sourceURL = $this->sourceURL; } else { echo 'No Dom Document available to addImageMetadata_datastream.<br>'; return false; } $datastream = $obj_dom->createElement("foxml:datastream"); $datastream->setAttribute("ID", "imageMetadata"); $datastream->setAttribute("STATE", "A"); $datastream->setAttribute("CONTROL_GROUP", "M"); $version = $obj_dom->createElement("foxml:datastreamVersion"); $obj_rootElement->appendChild($datastream); $version->setAttribute("ID", "imageMetadata.0"); $version->setAttribute("MIMETYPE", "text/xml"); $version->setAttribute("LABEL", "Image Metadata"); $obj_dom1 = new DomDocument("1.0", "UTF-8"); $obj_dom1->formatOutput = true; //begin writing Metadata $api = $obj_dom1->createElement("api:imageMetadata_record"); $api->setAttribute('xmlns:api', "http://www.apiaryproject.org/api"); //imageMetadata elements $h_element = $obj_dom1->createElement('api:h', $obj_height); $api->appendChild($h_element); $w_element = $obj_dom1->createElement('api:w', $obj_width); $api->appendChild($w_element); $URL_element = $obj_dom1->createElement('api:URL', htmlentities($obj_jp2URL)); $api->appendChild($URL_element); if ($obj_rft_id != null && $obj_rft_id != '') { $rft_id_element = $obj_dom1->createElement('api:rft_id', $obj_rft_id); $api->appendChild($rft_id_element); } $sourceURL_element = $obj_dom1->createElement('api:sourceURL', htmlentities($obj_sourceURL)); $api->appendChild($sourceURL_element); $obj_dom1->appendChild($api); $xml_file_pid = str_replace(':', '_', $obj_pid); $xml_file = '/var/www/drupal/sites/default/files/apiary_datastreams/' . $xml_file_pid . '-imageMetadata-content.xml'; if (file_exists($xml_file)) { unlink($xml_file); } $obj_dom1->save($xml_file); global $base_url; $xml_file_Url = $base_url . '/sites/default/files/apiary_datastreams/' . $xml_file_pid . '-imageMetadata-content.xml'; $imagecontent = $obj_dom->createElement('foxml:contentLocation'); $imagecontent->setAttribute("REF", "{$xml_file_Url}"); $imagecontent->setAttribute("TYPE", "URL"); $datastream->appendChild($version); $version->appendChild($imagecontent); $obj_rootElement->appendChild($datastream); return true; }
public function getCreateSitemap() { $urlroot = Config::get('app.url'); $types = Type::where('status', 1)->get(array('type', 'updated_at', 'id')); $pages = Post::where('status', 1)->get(array('slug', 'updated_at', 'type_id')); // $project = Project::get(array('slug', 'updated_at')); // var_dump($urlroot); die(); $xml = new DomDocument('1.0', 'utf-8'); $urlset = $xml->createElement('urlset'); $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9'); foreach ($types as $type) { $url = $xml->createElement('url'); $urlset->appendChild($url); $loc = $xml->createElement('loc'); $url->appendChild($loc); $loc->appendChild($text = $xml->createTextNode($urlroot . '/' . $type->type)); $lastmod = $xml->createElement('lastmod'); $url->appendChild($lastmod); $lastmod->appendChild($xml->createTextNode(date('Y-m-d', strtotime($type->updated_at)))); foreach ($pages as $post) { if ($post->type_id == $type->id) { $url = $xml->createElement('url'); $urlset->appendChild($url); $loc = $xml->createElement('loc'); $url->appendChild($loc); $loc->appendChild($text = $xml->createTextNode($urlroot . '/' . $type->type . '/' . $post->slug)); $lastmod = $xml->createElement('lastmod'); $url->appendChild($lastmod); $lastmod->appendChild($xml->createTextNode(date('Y-m-d', strtotime($post->updated_at)))); } } } $xml->appendChild($urlset); $xml->formatOutput = true; $xml->save('sitemap.xml'); if (!@fopen('sitemap.xml', "r")) { return Redirect::back()->with('error', 'ошибка при обновлении файла sitemap.xml'); } return Redirect::back()->with('success', 'файл sitemap.xml обновлен'); // return Response::download('sitemap.xml'); }
$htext = $doc->createTextNode($_POST['headline']); $head->appendChild($htext); //create navlabel $head = $doc->createElement("navigationlabel"); $root->appendChild($head); $htext = $doc->createTextNode($_POST['navlabel']); $head->appendChild($htext); //create abstract $abs = $doc->createElement("description"); $root->appendChild($abs); $abstext = $doc->createTextNode($_POST['description']); $abs->appendChild($abstext); //create body $body = $doc->createElement("body"); $root->appendChild($body); $cdata = $doc->createCdataSection($_POST['body']); $body->appendChild($cdata); //create status $stat = $doc->createElement("status"); $root->appendChild($stat); $stext = $doc->createTextNode($_POST['status']); $stat->appendChild($stext); //create pubDate $pub = $doc->createElement("pubdate"); $root->appendChild($pub); $pubtext = $doc->createTextNode($_POST['pubDate']); $pub->appendChild($pubtext); //write to the file $filename = "../xml/" . $id . ".xml"; $doc->save($filename); header("Location:webcopytool.php");
function addG($nom, $UID) { $xmldoc = new DomDocument('1.0'); $xmldoc->preserveWhiteSpace = false; $xmldoc->formatOutput = true; if ($xml = file_get_contents('../Ressources/Groupes.xml')) { $xmldoc->loadXML($xml, LIBXML_NOBLANKS); // find the headercontent tag $root = $xmldoc->getElementsByTagName('Groupes')->item(0); // create the <product> tag $categ = $xmldoc->createElement('Groupe'); $numAttribute = $xmldoc->createAttribute("id"); $numAttribute->value = maxId("Groupes"); $categ->appendChild($numAttribute); // add the product tag before the first element in the <headercontent> tag $root->insertBefore($categ, $root->firstChild); // create other elements and add it to the <product> tag. $nameElement = $xmldoc->createElement('nom'); $categ->appendChild($nameElement); $nameText = $xmldoc->createTextNode($nom); $nameElement->appendChild($nameText); $nameElement = $xmldoc->createElement('GID'); $categ->appendChild($nameElement); $nameText = $xmldoc->createTextNode(""); $nameElement->appendChild($nameText); $nameElement = $xmldoc->createElement('UID'); $categ->appendChild($nameElement); $nameText = $xmldoc->createTextNode($UID); $nameElement->appendChild($nameText); $xmldoc->save('../Ressources/Groupes.xml'); } }
private function saveCache() { if ($this->entitiesEdited || true) { //make a clean save $doc = new \DomDocument('1.0'); $doc->preserveWhiteSpace = false; $doc->formatOutput = true; $doc->loadXML($this->xml->saveXml()); $doc->save($this->cacheFile); //file_put_contents($this->cacheFile, $this->xml->saveXml()); } }
function crear() { set_time_limit(0); $ruta = "musica"; $GLOBALS['contador'] = 1; //Empesamos la estructura del archivo xml $xml = new DomDocument('1.0'); $playlist = $xml->createElement('albumList'); $playlist = $xml->appendChild($playlist); // comprobamos si lo que nos pasan es un direcotrio if (is_dir($ruta)) { // Abrimos el directorio y comprobamos que if ($aux = opendir($ruta)) { while (($archivo = readdir($aux)) !== false) { // Si quisieramos mostrar todo el contenido del directorio pondrÃÂamos lo siguiente: // echo '<br />' . $file . '<br />'; // Pero como lo que queremos es mostrar todos los archivos excepto "." y ".." if ($archivo != "." && $archivo != "..") { $ruta_completa = $ruta . '/' . $archivo; //echo "Esto: ".$ruta_completa."<br>"; if (is_dir($ruta_completa)) { // Abrimos la nueva carpeta, esta sera el nombre del album if ($aux2 = opendir($ruta_completa)) { //echo "Folder: ".$archivo."<br>"; //Aui se empiezan a crear los albums $libro = $xml->createElement('album'); //se empieza a iterar desde el album $libro = $playlist->appendChild($libro); $autor = $xml->createElement('albumID', "{$GLOBALS['contador']}"); $autor = $libro->appendChild($autor); $titulo = $xml->createElement('albumTitle', htmlspecialchars(utf8_encode($archivo))); $titulo = $libro->appendChild($titulo); $anio = $xml->createElement('albumArtist', 'unknown'); $anio = $libro->appendChild($anio); //$albumFolder = $xml->createElement('albumFolder','../data/ACDC/Back In Black/');//No se aun que es esto,parece ser la ubicacion de las imagenes $albumFolder = $xml->createElement('albumFolder', '/images'); $albumFolder = $libro->appendChild($albumFolder); $albumTracks = $xml->createElement('albumTracks'); //Empieza la lista de canciones $albumTracks = $libro->appendChild($albumTracks); $no_cancion = 1; while (($archivo2 = readdir($aux2)) !== false) { if ($archivo2 != "." && $archivo != "..") { $ruta_completa2 = $ruta_completa . '/' . $archivo2; if (is_dir($ruta_completa2)) { } else { if (substr("{$ruta_completa2}", -3, 3) == "mp3") { //El sistema solo soporta archivos con expencion mp3 $track = $xml->createElement('track'); $track = $albumTracks->appendChild($track); $trackID = $xml->createElement('trackID', "{$no_cancion}"); $trackID = $track->appendChild($trackID); $trackFile = $xml->createElement('trackFile', htmlspecialchars(utf8_encode($ruta_completa2))); //Ubicacion del archivo $trackFile = $track->appendChild($trackFile); $trackTitle = $xml->createElement('trackTitle', htmlspecialchars(utf8_encode($archivo2))); //Nombre del archivo $trackTitle = $track->appendChild($trackTitle); $trackArtist = $xml->createElement('trackArtist', "Unknow"); $trackArtist = $track->appendChild($trackArtist); //Calcular el timpo de la cancion $mp3file = new MP3File(htmlspecialchars($ruta_completa2)); $duration2 = $mp3file->getDuration(); //(slower) for VBR (or CBR) $trackLengh = $xml->createElement('trackLengh', MP3File::formatTime($duration2)); $trackLengh = $track->appendChild($trackLengh); $trackFileSize = $xml->createElement('trackFileSize', formatSizeUnits(filesize(htmlspecialchars($ruta_completa2)))); //Tamaño del archivo $trackFileSize = $track->appendChild($trackFileSize); //echo "Ubicacion del archivo: ".$ruta_completa2."<br>"; $GLOBALS['contador']++; $no_cancion++; } } //Termina else carga de archivos } } //Esto va despues del while $albumTracksCount = $xml->createElement('albumTracksCount', $no_cancion - 1); $albumTracksCount = $libro->appendChild($albumTracksCount); $no_cancion = 1; $albumCover = $xml->createElement('albumCover', "images/disco.jpg"); $albumCover = $libro->appendChild($albumCover); closedir($aux2); } } else { //No son carpetas, por lo tanto no mostramos nada } } } closedir($aux); } } //Creamos el archivo $xml->formatOutput = true; $el_xml = $xml->saveXML(); $xml->save('xml/playlistAllAlbums.xml'); }
$attributes = $xml->createElement("attributes"); $attributes = $class->appendChild($attributes); for ($i = 0; $i < $nbAttr; $i++) { $attribute = $xml->createElement("attribute"); $attribute = $attributes->appendChild($attribute); $attrName = $xml->createElement("name", $generatedClass->atribut[$i]->nama); $attrName = $attribute->appendChild($attrName); $attrValue = $xml->createElement("value", $generatedClass->atribut[$i]->nilai); $attrValue = $attribute->appendChild($attrValue); } $methods = $xml->createElement("methods"); $methods = $class->appendChild($methods); for ($i = 0; $i < $nbMethod; $i++) { $method = $xml->createElement("method"); $method = $methods->appendChild($method); $methodName = $xml->createElement("name", $generatedClass->method[$i]->name); $methodName = $method->appendChild($methodName); $arguments = $xml->createElement("params"); $arguments = $method->appendChild($arguments); for ($j = 0; $j < count($generatedClass->method[$i]->parameter); $j++) { $param = $xml->createElement("param", $generatedClass->method[$i]->parameter[$j]); $param = $arguments->appendChild($param); } $code = $xml->createElement("code", $generatedClass->method[$i]->content); $code = $method->appendChild($code); } $xml->FormatOutput = true; $xml->preserveWhiteSpace = false; $save = $xml->saveXML(); $xml->save("../xml/generatedClass.xml"); header("location:Parser.php");
/** * Запускает установку всех не установленных компонентов */ private function installComponents() { if ($this->checkDone(__METHOD__)) { return true; } $instructions = $this->temp_dir . "/update-instructions.xml"; $doc = new DOMDocument('1.0', 'utf-8'); if (!$doc->load($instructions)) { throw new Exception("Не удается загрузить инструкции по обновлению"); } $xpath = new DOMXPath($doc); $components = $xpath->query("//package/component[not(@installed)]"); foreach ($components as $component) { $name = $component->getAttribute('name'); if ($xpath->query("//package/component[@installed]")->length == 0 && $this->getComponentOffset($name) == 0) { $this->flushLog("Установка компонентов..."); } do { $old_offset = $this->getComponentOffset($name); if ($old_offset == 0) { $this->flushLog("Установка компонента {$name}..."); // При первом запуске удаляем файлы, которые предназначены только для установки, и уже существуют if (!$this->install_mode) { $component_config = $this->temp_dir . "/{$name}/{$name}.xml"; $source = new DomDocument(); $source->load($component_config); $source_xpath = new DOMXPath($source); $to_del = $source_xpath->query('//file[@only_install]'); foreach ($to_del as $file) { $path = $file->textContent; if (file_exists(CURRENT_WORKING_DIR . $path)) { $file->parentNode->removeChild($file); } else { $file->removeAttribute("only_install"); } } $source->save($component_config); } } $result = $this->execSubProcess('install-component', array('component' => $name)); // Перезагружаем состояние $this->loadState(); $new_offset = $this->getComponentOffset($name); if ($new_offset >= $old_offset + self::$split_block_size && !$this->cli_mode) { return false; } } while ($new_offset >= $old_offset + self::$split_block_size); $this->flushLog("Компонент {$name} установлен."); $component->setAttribute('installed', true); $doc->save($instructions); if (!$this->cli_mode) { return false; } } $this->flushLog("Все компоненты были установлены."); $this->setDone(__METHOD__); return true; }
$xml_properties = $doc->createElement('properties'); $xml_number = $doc->createElement('number', $chart); $xml_properties->appendChild($xml_number); $xml_width = $doc->createElement('width', $width); $xml_properties->appendChild($xml_width); $xml_height = $doc->createElement('height', $height); $xml_properties->appendChild($xml_height); $xml_tiles = $doc->createElement('tiles', $numTilesLevel); $xml_properties->appendChild($xml_tiles); $xml_xtiles = $doc->createElement('xtiles', $x); $xml_properties->appendChild($xml_xtiles); $xml_ytiles = $doc->createElement('ytiles', $y); $xml_properties->appendChild($xml_ytiles); $xml_tilesize = $doc->createElement('tilesize', $tileSize); $xml_properties->appendChild($xml_tilesize); $xml_chart->appendChild($xml_properties); $doc->appendChild($xml_chart); echo $doc->saveXML(); $doc->save($path . '/' . $chart . '.xml'); } function getIndexNumber($xc, $yc) { global $x, $y, $numTiles, $numTilesLevel; #echo"<br>XC: $xc <-> YC: $yc<br>x: $x <-> y: $y<br>"; $ind = $xc + ($yc - 1) * $x + ($numTiles - $numTilesLevel); return $ind; } function getTileGroupNumber($t) { return floor($t / 256); }
/** getEntireCategoryTree Retrieves the entire category tree from eBay API and saves it locally in an XML file */ function getEntireCategoryTree($devID, $appID, $certID, $compatabilityLevel, $siteID, $userToken, $serverUrl) { //Build the request Xml string $requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>'; $requestXmlBody .= '<GetCategoriesRequest xmlns="urn:ebay:apis:eBLBaseComponents">'; $requestXmlBody .= "<RequesterCredentials><eBayAuthToken>{$userToken}</eBayAuthToken></RequesterCredentials>"; $requestXmlBody .= "<DetailLevel>ReturnAll</DetailLevel>"; //get the entire tree $requestXmlBody .= "<Item><Site>{$siteID}</Site></Item>"; $requestXmlBody .= "<ViewAllNodes>1</ViewAllNodes>"; //Gets all nodes not just leaf nodes $requestXmlBody .= '</GetCategoriesRequest>'; //Create a new eBay session with all details pulled in from included keys.php $session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, 'GetCategories'); $responseXml = $session->sendHttpRequest($requestXmlBody); if (stristr($responseXml, 'HTTP 404') || $responseXml == '') { die('<P>Error sending request'); } //Xml string is parsed and creates a DOM Document object $responseDoc = new DomDocument(); $responseDoc->loadXML($responseXml); //save the tree to local file $responseDoc->save('CatTree.xml'); //return the DOM Document return $responseDoc; }
// find the headercontent tag $root = $xmldoc->getElementsByTagName('SegmentsPath')->item(0); // create the <product> tag $product = $xmldoc->createElement('Segment'); $numAttribute = $xmldoc->createAttribute("value"); $numAttribute->value = $folderName; $product->appendChild($numAttribute); // add the product tag before the first element in the <headercontent> tag $root->insertBefore($product, $root->firstChild); // create other elements and add it to the <product> tag. $nameElement = $xmldoc->createElement('High'); $product->appendChild($nameElement); $nameText = $xmldoc->createTextNode("/high/output1.mp4"); $nameElement->appendChild($nameText); $categoryElement = $xmldoc->createElement('Medium'); $product->appendChild($categoryElement); $categoryText = $xmldoc->createTextNode("/high/output2.mp4"); $categoryElement->appendChild($categoryText); $availableElement = $xmldoc->createElement('Low'); $product->appendChild($availableElement); $availableAttribute = $xmldoc->createTextNode("/high/output3.mp4"); $availableElement->appendChild($availableAttribute); $xmldoc->save('infopk.xml'); } # } } } else { echo "Invalid file"; } fclose($logfp); exit;