Modx ошибка синтаксического анализа

  • 14651

  • 46 Posts
  • Send PM

Здравствуйте, уважаемые коллеги! Подскажите, пожалуйста:
Сделал вот что:

Сниппет sitemap работает несколько быстрее Ditto, его мы и рассмотрим. Для его установки необходимо создать сниппет sitemap и скопировать в него содержимое этого файла.

Для того чтобы сгенерировать карту сайта, нужно следующее:

1) Создать TV параметры sitemap_changefreq и sitemap_priority

sitemap_changefreq
Тип: DropDown List Menu
Возможные значения : always||hourly||daily||weekly||monthly||yearly||never
Значение по умолчанию : поставьте наиболее актуальный для вашего сайта период обновления.

sitemap_priority
Тип: DropDown List Menu
Возможные значения : .1||.2|| .3|| .5|| .6|| .7|| .8|| .9 || 1
Значение по умолчанию : .5 (можете поставить любое другое).

2) Создать новый документ в корне сайта

3) Установить “Псевдоним” = sitemap.xml(Семантические URL должны быть включены)

4) Выбрать шаблон “(blank)” в настройках документа-общие

5) Если HTML-редактор контента включен, отключить его

6) Выбрать тип содержимого “text/xml’ в настройках страницы

7) Вставить в “Содержимое страницы”

8) В контент внести [[sitemap]]

9) Обновить сайт.

Код сниппета

<?php
/**
 * GoogleSiteMap
 *
 * Copyright 2009 by Shaun McCormick <shaun@collabpad.com>
 *
 * - Based on Michal Till's MODx Evolution GoogleSiteMap_XML snippet
 *
 * GoogleSiteMap is free software; you can redistribute it and/or modify it
<?php
/*
==================================================
	sitemap
==================================================

Outputs a machine readable site map for search
engines and robots. Supports the following
formats:

- Sitemap Protocol used by Google Sitemaps
  (http://www.google.com/webmasters/sitemaps/)

- URL list in text format
  (e.g. Yahoo! submission)

Author: Grzegorz Adamiak [grad]
Version: 1.0.8 @ 22-AUG-2008
License: LGPL
MODx: 0.9.2.1, 0.9.6.1

History:
# 1.0.8
- excludeTemplates can now also be specified as a template ID instead of template name. 
  Useful if you change the names of your templates frequently. (ncrossland)
  e.g. &excludeTemplates=`myTemplateName,3,4`
# 1.0.7
- Unpublished and deleted documents were showing up in the sitemap. Even though they could not be viewed, 
  they were showing up as broken links to search engines. (ncrossland)
# 1.0.6
- Add optional parameter (excludeWeblinks) to exclude weblinks from the sitemap, since they often point to external
  sites (which don't belong on your sitemap), or redirecting to other internal pages (which are already
  in the sitemap). Google Webmaster Tools generates warnings for excessive redirects.	
  Default is false - e.g. default behaviour remains unchanged. (ncrossland)
# 1.0.5
- Modification about non searchable documents, as suggested by forum user JayBee
  (http://modxcms.com/forums/index.php/topic,5754.msg99895.html#msg99895)
# 1.0.4 (By Bert Catsburg, bert@catsburg.com)
- Added display option 'ulli'. 
  An <ul><li> list of all published documents.
# 1.0.3
- Added ability to specify the XSL URL - you don't always need one and it 
  seems to create a lot of support confusion!
  It is now a parameter (&xsl=``) which can take either an alias or a doc ID (ncrossland)
- Modifications suggested by forum users Grad and Picachu incorporated
  (http://modxcms.com/forums/index.php/topic,5754.60.html)
# 1.0.2
- Reworked fetching of template variable value to
  get INHERITED value.
# 1.0.1
- Reworked fetching of template variable value,
  now it gets computed value instead of nominal;
  however, still not the inherited value.
# 1.0
- First public release.

TODO:
- provide output for ROR
--------------------------------------------------
*/

/* Parameters
----------------------------------------------- */

# $startid [ int ]
# Id of the 'root' document from which the sitemap
# starts.
# Default: 0

$startid = (isset($startid)) ? $startid : 0;

# $format [ sp | txt | ror ]
# Which format of sitemap to use:
# - sp <- Sitemap Protocol used by Google
# - txt <- text file with list of URLs
# TODO - ror <- Resource Of Resources
# Default: sp

$format = (isset($format) && ($format != 'ror')) ? $format : 'sp';

# $priority [ str ]
# Name of TV which sets the relative priority of
# the document. If there is no such TV, this
# parameter will not be used.
# Default: sitemap_priority

$priority = (isset($priority)) ? $priority : 'sitemap_priority';

# $changefreq [ str ]
# Name of TV which sets the change frequency. If
# there is no such TV this parameter will not be
# used.
# Default: sitemap_changefreq

$changefreq = (isset($changefreq)) ? $changefreq : 'sitemap_changefreq';

# $excludeTemplates [ str ]
# Documents based on which templates should not be
# included in the sitemap. Comma separated list
# with names of templates.
# Default: empty

$excludeTemplates = (isset($excludeTemplates)) ? $excludeTemplates : array();

# $excludeTV [ str ]
# Name of TV (boolean type) which sets document
# exclusion form sitemap. If there is no such TV
# this parameter will not be used.
# Default: 'sitemap_exclude'

$excludeTV = (isset($excludeTV)) ? $excludeTV : 'sitemap_exclude';

# $xsl [ str ] 
# URL to the XSL style sheet
# or
# $xsl [ int ]
# doc ID of the XSL style sheet

$xsl = (isset($xsl)) ? $xsl : '';
if (is_numeric($xsl)) { $xsl = $modx->makeUrl($xsl); }


# $excludeWeblinks [ bool ]
# Should weblinks be excluded?
# You may not want to include links to external sites in your sitemap,
# and Google gives warnings about multiple redirects to pages 
# within your site.
# Default: false
$excludeWeblinks = (isset($excludeWeblinks)) ? $excludeWeblinks : false;


/* End parameters
----------------------------------------------- */

# get list of documents
# ---------------------------------------------
$docs = getDocs($modx,$startid,$priority,$changefreq,$excludeTV);


# filter out documents by template or TV
# ---------------------------------------------
// get all templates
$select = $modx->db->select("id, templatename", $modx->getFullTableName('site_templates'));
while ($query = $modx->db->getRow($select)) {
	$allTemplates[$query['id']] = $query['templatename'];
}

$remainingTemplates = $allTemplates;

// get templates to exclude, and remove them from the all templates list
if (!empty ($excludeTemplates)) {
	
	$excludeTemplates = explode(",", $excludeTemplates);	
	
	// Loop through each template we want to exclude
	foreach ($excludeTemplates as $template) {
		$template = trim($template);
		
		// If it's numeric, assume it's an ID, and remove directly from the $allTemplates array
		if (is_numeric($template) && isset($remainingTemplates[$template])) {
			unset($remainingTemplates[$template]);
		} else if (trim($template) && in_array($template, $remainingTemplates)) { // If it's text, and not empty, assume it's a template name
			unset($remainingTemplates[array_search($template, $remainingTemplates)]);			
		}
	} // end foreach
}

$output= array();
// filter out documents which shouldn't be included
foreach ($docs as $doc)
{
	if (isset($remainingTemplates[$doc['template']]) && !$doc[$excludeTV] && $doc['published'] && $doc['template']!=0 && $doc['searchable']) {
		if (!$excludeWeblinks || ($excludeWeblinks && $doc['type'] != 'reference')) {
			$output[] = $doc;		
		}
	}
}
$docs = $output;
unset ($output, $allTemplates, $excludeTemplates);


# build sitemap in specified format
# ---------------------------------------------

switch ($format)
{
	// Next case added in version 1.0.4
	case 'ulli': // UL List
		$output .= "<ul class="sitemap">n";
		// TODO: Sort the array on Menu Index
		// TODO: Make a nested ul-li based on the levels in the document tree.
		foreach ($docs as $doc)
		{
			$s  = "  <li class="sitemap">";
			$s .= "<a href="[(site_url)][~" . $doc['id'] . "~]" class="sitemap">" . $doc['pagetitle'] . "</a>";
			$s .= "</li>n";
			$output .= $s;
		} // end foreach
		$output .= "</ul>n";
		break;
		
	case 'txt': // plain text list of URLs

		foreach ($docs as $doc)
		{
			$url = '[(site_url)][~'.$doc['id'].'~]';

			$output .= $url."n";
		} // end foreach
		break;

	case 'ror': // TODO
	default: // Sitemap Protocol

	
	$output = '<?xml version="1.0" encoding="UTF-8"?>'."n";
	if ($xsl != '') {
		$output .='<?xml-stylesheet type="text/xsl" href="'.$xsl.'"?>'."n";
	}
	$output .='<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."n";
	
	
	foreach ($docs as $doc)	{
		$url = '[(site_url)][~'.$doc['id'].'~]';
		$date = $doc['editedon'];
		$date = date("Y-m-d", $date);
		$docPriority = ($doc[$priority]) ? $doc[$priority] : 0; // false if TV doesn't exist
		$docChangefreq = ($doc[$changefreq]) ? $doc[$changefreq] : 0; // false if TV doesn't exist

		$output .= "t".'<url>'."n";
		$output .= "tt".'<loc>'.$url.'</loc>'."n";
		$output .= "tt".'<lastmod>'.$date.'</lastmod>'."n";
		$output .= ($docPriority) ? ("tt".'<priority>'.$docPriority.'</priority>'."n") : ''; // don't output anything if TV doesn't exist
		$output .= ($docChangefreq) ? ("tt".'<changefreq>'.$docChangefreq.'</changefreq>'."n") : ''; // don't output anything if TV doesn't exist
		$output .= "t".'</url>'."n";
	} // end foreach
	$output .= '</urlset>';

} // end switch

return $output;

# functions
# ---------------------------------------------

# gets (inherited) value of template variable
function getTV($modx,$docid,$doctv)
{
/* apparently in 0.9.2.1 the getTemplateVarOutput function doesn't work as expected and doesn't return INHERITED value; this is probably to be fixed for next release; see http://modxcms.com/bugs/task/464
	$output = $modx->getTemplateVarOutput($tv,$docid);
	return $output[$tv];
*/
	
	while ($pid = $modx->getDocument($docid,'parent'))
	{
		$tv = $modx->getTemplateVar($doctv,'*',$docid);
		if (($tv['value'] && substr($tv['value'],0,8) != '@INHERIT') or !$tv['value']) // tv default value is overriden (including empty)
		{
			$output = $tv['value'];
			break;
		}
		else // there is no parent with default value overriden 
		{
			$output = trim(substr($tv['value'],8));
		}
		$docid = $pid['parent']; // move up one document in document tree
	} // end while
	
	return $output;
}

# gets list of published documents with properties
function getDocs($modx,$startid,$priority,$changefreq,$excludeTV)
{
	// get children documents
	$docs = $modx->getActiveChildren($startid,'menuindex','asc','id,editedon,template,published,searchable,pagetitle,type'); 
	// add sub-children to the list
	foreach ($docs as $key => $doc)
	{
		$id = $doc['id'];
		$docs[$key][$priority] = getTV($modx,$id,$priority); // add priority property
		$docs[$key][$changefreq] = getTV($modx,$id,$changefreq); // add changefreq property
		$docs[$key][$excludeTV] = getTV($modx,$id,$excludeTV); // add excludeTV property
		
		if ($modx->getActiveChildren($id))
			$docs = array_merge($docs, getDocs($modx,$id,$priority,$changefreq,$excludeTV));
	} // end foreach
	return $docs;
}
?>

В итоге не работает нихрена. «Ошибка синтаксического анализа XML: элемент не найден
Адрес: http://mamatalk.info/sitemap.xml
Строка 1, символ 1:

Подскажите как это исправить. Версия Modx 1.0.1

    не просто дизайнеру копаться в скриптах…спасибо за понимание

    • 29487

    • 385 Posts
    • Send PM

    • 14651

    • 46 Posts
    • Send PM

    В сниппете она есть на том месте..не пойму чего она не отображается в коде здесь?

      не просто дизайнеру копаться в скриптах…спасибо за понимание

      • 29487

      • 385 Posts
      • Send PM

      • 14651

      • 46 Posts
      • Send PM

      Спасибулички, Temus! Очень помогли

        не просто дизайнеру копаться в скриптах…спасибо за понимание

        • 16313

        • 71 Posts
        • Send PM

        У меня тоже проблемка с sitemap.xml
        http://assistpro.com.ua/sitemap.xml

        Выскакивает вот такая ошибка:
        Ошибка синтаксического анализа XML: объявление XML или текста не в начале сущности
        Адрес: http://assistpro.com.ua/sitemap.xml
        Строка 2, символ 1:<?xml version=»1.0″ encoding=»UTF-8″?>

        Sitemap 1.0.8 брал от сюда:
        http://modxcms.com/extras/package/410

        На сколько я понимаю, проблема в том, что первой в файле стоит пустая строка.
        Как ее удалить?

          • 16313

          • 71 Posts
          • Send PM

          Please help rolleyes

            • 16313

            • 71 Posts
            • Send PM

            Проблему решил. Оказалось что первую строку в xml файле вставлял плагин EmailDefender sad

              • 9320

              • 1 Posts
              • Send PM

              Ребят помогите с sitemap.xml
              использую http://modxcms.com/extras/package/?package=410

              проблему решил:) проблема появилась из-за моей не внимательности:(

                • 31978

                • 39 Posts
                • Send PM

                Добрый день!

                Тоже проблемка с указанным сниппетом.

                Выдает ошибку

                PHP error debug
                Error: date() [function.date]: It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ’Europe/Moscow’ for ’MSK/3.0/no DST’ instead
                Error type/ Nr.: Warning — 2
                File: /home/u111111/site.ru/www/manager/includes/document.parser.class.inc.php(770) : eval()’d code
                Line: 226

                Что я делаю не так?

                  Когда есть желание — появляются возможности. Когда нет желания — появляются причины.

                  I’m currently having an issue with MODx, when trying to access my website. It gives the following error:

                   « MODx Parse Error »
                     MODx encountered the following error while attempting to parse the requested resource:
                    « PHP Parse Error »
                   PHP error debug
                    Error:    Function split() is deprecated   
                    Error type/ Nr.:  - 8192   
                    File:     /mnt/stor2-wc1-dfw1/371478/401863/www.stonero.com/web/content/manager    /includes/document.parser.class.inc.php     
                    Line:     844  
                    Line 844 source:  $tempSnippetParams= split($splitter, $tempSnippetParams);    
                  
                  Parser timing
                  MySQL:  0.0283 s    (3 Requests)
                  PHP:    0.0430 s     
                  Total:  0.0713 s
                  

                  It started as a problem on a subpage, and when I cleared the cache it just broke the entire site. Can someone help me out?

                  Thanks in advance,
                  Chris

                  asked Jul 1, 2013 at 19:44

                  ChrisK's user avatar

                  1

                  The PHP version on your web server does not support the split() function. It’s likely you’ve installed a snippet or plugin coded for an outdated PHP version — or your web host has upgraded to a newer PHP version.

                  You’ll need to find this snippet/plugin and replace it with explode(). Easiest way would be to search the relevant tables in the database for the line:

                  $tempSnippetParams= split($splitter, $tempSnippetParams);
                  

                  answered Jul 2, 2013 at 2:43

                  okyanet's user avatar

                  okyanetokyanet

                  3,0861 gold badge22 silver badges16 bronze badges

                  0

                  Версия MODX: Все

                  При вызове снипета pdoSitemap, генерируемая карта сайта выдает ошибку:
                  Ошибка синтаксического анализа XML: объявление XML или текста не в начале сущности
                  Строка 2, символ 1:<?xml version=«1.0» encoding=«UTF-8»?>
                  ^
                  Может кто сталкивался с данной проблемой?


                  Awful
                  14.12.17 в 00:12

                  Нахальный ответ? — «Апгрейд» Evolution мертв.

                  Более полезный ответ, проверьте системные настройки modx, в Revolution вы можете указать modx, какие разрешения пытаться установить для файлов, я предполагаю, что, возможно, вы случайно установили их в 000, если это то, что вы подразумеваете под этим: «у них есть какие-либо набор разрешений «

                  Если это не работает / вы впадаете в отчаяние, отключите все кэширование и тестирование или, если возможно, [еще не знаком с evo] установите этот ресурс, чтобы он не кэшировался.

                  Хотя что-то странное происходит, пожалуйста, подтвердите; страница индекса будет кэширована, но без разрешений, т.е. 000, последующие страницы будут кэшированы, но установлены ли правильные разрешения? т.е. 666 [или 644/ что угодно]

                  Обновление от 4 июня 2010 г.: Похоже, это ошибка в MODx v 1.0.3, не имеющая отношения к функции implode, а скорее проблема с несоответствием типов данных в результирующем предложении фильтра. Ошибка зарегистрирована в JIRA: MODX-2035.

                  Привет, я не могу в жизни понять это, может быть, кто-то может помочь.

                  Используя MODX, форма принимает пользовательские критерии для создания фильтра и возвращает список документов. Форма представляет собой одно текстовое поле и несколько флажков. Если публикуются данные как текстового поля, так и флажка, функция работает нормально; если публикуются только данные флажка, функция работает нормально; но если публикуются только данные текстового поля, modx выдает следующую ошибку:

                  Ошибка: implode() [function.implode]: переданы недопустимые аргументы.

                  Я протестировал это вне modx с плоскими файлами, и все работает нормально, что заставило меня предположить, что в modx существует ошибка. Но я не уверен. Вот мой код:

                  <?php
                  $order = array('price ASC'); //default sort order  
                  if(!empty($_POST['tour_finder_duration'])){ //duration submitted  
                   $days = htmlentities($_POST['tour_finder_duration']); //clean up post  
                   array_unshift($order,"duration DESC"); //add duration sort before default  
                   $filter[] = 'duration,'.$days.',4'; //add duration to filter[] (field,criterion,mode)  
                   $criteria[] = 'Number of days: <strong>'.$days.'</strong>'; //displayed on results page  
                  }  
                  
                  if(!empty($_POST['tour_finder_dests'])){ //destination/s submitted  
                   $dests = $_POST['tour_finder_dests'];  
                   foreach($dests as $value){ //iterate through dests array  
                    $filter[] = 'searchDests,'.htmlentities($value).',7'; //add dests to filter[]  
                    $params['docid'] = $value;  
                    $params['field'] = 'pagetitle';  
                    $pagetitle = $modx->runSnippet('GetField',$params);  
                    $dests_array[] = '<a href="[~'.$value.'~]" title="Read more about '.$pagetitle.'"     class="tourdestlink">'.$pagetitle.'</a>';  
                   }  
                   $dests_array = implode(', ',$dests_array);  
                   $criteria[] = 'Destinations: '.$dests_array; //displayed on results page  
                  }  
                  
                  if(is_array($filter)){  
                   $filter = implode('|',$filter);//pipe-separated string  
                  }  
                  if(is_array($order)){  
                   $order = implode(',',$order);//comma-separated string  
                  }  
                  if(is_array($criteria)){  
                   $criteria = implode('<br />',$criteria);  
                  }  
                  
                  echo '<br />Order: '.$order.'<br /> Filter: '.$filter.'<br /> Criteria: '.$criteria;
                  
                  //next: extract docs using $filter and $order, display user's criteria using $criteria...  
                  ?>
                  

                  Оператор echo отображается над сообщением об ошибке MODX, а массив $filter корректно схлопывается.

                  Любая помощь спасет мой компьютер от вылета в окно.

                  Благодарность

                  2 ответа

                  Я думаю, ваша проблема здесь:

                  $dests_array = implode(', ',$dests_array); 
                  

                  $dest_array может быть пустым и даже не инициализированным, если $dests пуст.


                  0

                  Arkh
                  31 Май 2010 в 16:49

                  Это действительно должно быть размещено на форумах MODx. Мне нравится stackoverflow, но MODx более нишевый.


                  0

                  Everett
                  27 Авг 2010 в 10:38

                  Понравилась статья? Поделить с друзьями:
                • Modx вывод ошибок php
                • Mme ошибка внутреннего устройства adobe audition
                • Mmd ошибка не удалось запустить приложение
                • Mmcm ошибка 80010017 на ps3 как исправить
                • Mmccore ahk ошибка калина