PHP-Fusion
v.7.01
AP-Fusion
v7.02.04
Pimped-Fusion-AP
v0.09.03
мая 25 2012 15:17:54
Навигация
· Новости
· Статьи
· Скачать
· Форум
· Ссылки
· Категории новостей
· Обратная связь
· Галерея
· Поиск
· Гостевая
· Коллекция аватар
· CMS AP-Fusion. Отличия от PHP-Fusion
· Javascript справочник
· Разное
· Техника
Сейчас на сайте
· Гостей: 5

· Пользователей: 0

· Всего пользователей: 445
· Новый пользователь: vesuvius
Информеры
Загрузка файлов  +  -
Бытовая техника:  +  
Лента alipapa.ru
Карпаты. Верховина.
Карпаты. Драгобрат.
Карпаты. Яремче, Яблунецкий перевал.
dbForge Studio for MySQL вместо PHPMyAdmin
Облачные технологии - насколько это серьезно?
Как распределяется вес по сайту

Совместимость CMS
Solomono.ru - сервис для веб-мастера
Микроразметка веб-страниц.
АГС - не приговор.

Немного о политике.
Что такое АГС и как с ним бороться?
Долгожданный АП PR

PR Google: 9 месяцев без апдейта
Поведенческий фактор - модная тенденция?
Wi-Fi дома. Что делать, если 192.168.0.1 занято?

Ускоренная переиндексация страниц в Яндексе
Как я ставил винду на нетбук.
ROOKEE - инструмент оптимизатора.
Строим рейтинг-каталог
Ссылки  +  -
Блоги
Alipapa
» Блог Алипапы
lom
» Блог Лома

xslt_process

(PHP 4 >= 4.0.3)

xslt_process -- Perform an XSLT transformation

Description

mixed xslt_process ( resource xh, string xmlcontainer, string xslcontainer [, string resultcontainer [, array arguments [, array parameters]]] )

The xslt_process() function is the crux of the new XSLT extension. It allows you to perform an XSLT transformation using almost any type of input source - the containers. This is accomplished through the use of argument buffers -- a concept taken from the Sablotron XSLT processor (currently the only XSLT processor this extension supports). The input containers default to a filename 'containing' the document to be processed. The result container defaults to a filename for the transformed document. If the result container is not specified - i.e. NULL - than the result is returned.

Внимание

This function has changed its arguments, since version 4.0.6. Do NOT provide the actual XML or XSL content as 2nd and 3rd argument, as this will create a segmentation fault, in Sablotron versions up to and including 0.95.

Containers can also be set via the $arguments array (see below).

The simplest type of transformation with the xslt_process() function is the transformation of an XML file with an XSLT file, placing the result in a third file containing the new XML (or HTML) document. Doing this with sablotron is really quite easy...

Пример 1. Using the xslt_process() to transform an XML file and a XSL file to a new XML file

<?php

// Allocate a new XSLT processor
$xh = xslt_create ();

// Process the document
if ( xslt_process ( $xh , 'sample.xml' , 'sample.xsl' , 'result.xml' )) {
    echo
"SUCCESS, sample.xml was transformed by sample.xsl into result.xml" ;
    echo
", result.xml has the following contents\n<br />\n" ;
    echo
"<pre>\n" ;
    
readfile ( 'result.xml' );
    echo
"</pre>\n" ;
} else {
    echo
"Sorry, sample.xml could not be transformed by sample.xsl into" ;
    echo
"  result.xml the reason is that " . xslt_error ( $xh ) . " and the " ;
    echo
"error code is " . xslt_errno ( $xh );
}

xslt_free ( $xh );

?>

While this functionality is great, many times, especially in a web environment, you want to be able to print out your results directly. Therefore, if you omit the third argument to the xslt_process() function (or provide a NULL value for the argument), it will automatically return the value of the XSLT transformation, instead of writing it to a file...

Пример 2. Using the xslt_process() to transform an XML file and a XSL file to a variable containing the resulting XML data

<?php

// Allocate a new XSLT processor
$xh = xslt_create ();

// Process the document, returning the result into the $result variable
$result = xslt_process ( $xh , 'sample.xml' , 'sample.xsl' );
if (
$result ) {
    echo
"SUCCESS, sample.xml was transformed by sample.xsl into the \$result" ;
    echo
" variable, the \$result variable has the following contents\n<br />\n" ;
    echo
"<pre>\n" ;
    echo
$result ;
    echo
"</pre>\n" ;
} else {
    echo
"Sorry, sample.xml could not be transformed by sample.xsl into" ;
    echo
"  the \$result variable the reason is that " . xslt_error ( $xh );
    echo
" and the error code is " . xslt_errno ( $xh );
}

xslt_free ( $xh );

?>

The above two cases are the two simplest cases there are when it comes to XSLT transformation and I'd dare say that they are the most common cases, however, sometimes you get your XML and XSLT code from external sources, such as a database or a socket. In these cases you'll have the XML and/or XSLT data in a variable -- and in production applications the overhead of dumping these to file may be too much. This is where XSLT's "argument" syntax, comes to the rescue. Instead of files as the XML and XSLT arguments to the xslt_process() function, you can specify "argument place holders" which are then substituted by values given in the arguments array (5th parameter to the xslt_process() function). The following is an example of processing XML and XSLT into a result variable without the use of files at all.

Пример 3. Using the xslt_process() to transform a variable containing XML data and a variable containing XSL data into a variable containing the resulting XML data

<?php
// $xml and $xsl contain the XML and XSL data

$arguments = array(
     
'/_xml' => $xml ,
     
'/_xsl' => $xsl
);

// Allocate a new XSLT processor
$xh = xslt_create ();

// Process the document
$result = xslt_process ( $xh , 'arg:/_xml' , 'arg:/_xsl' , NULL , $arguments );
if (
$result ) {
    echo
"SUCCESS, sample.xml was transformed by sample.xsl into the \$result" ;
    echo
" variable, the \$result variable has the following contents\n<br />\n" ;
    echo
"<pre>\n" ;
    echo
$result ;
    echo
"</pre>\n" ;
} else {
    echo
"Sorry, sample.xml could not be transformed by sample.xsl into" ;
    echo
"  the \$result variable the reason is that " . xslt_error ( $xh );
    echo
" and the error code is " . xslt_errno ( $xh );
}
xslt_free ( $xh );
?>

Finally, the last argument to the xslt_process() function represents an array for any top-level parameters that you want to pass to the XSLT document. These parameters can then be accessed within your XSL files using the <xsl:param name="parameter_name"> instruction. The parameters must be UTF-8 encoded and their values will be interpreted as strings by the Sablotron processor. In other words - you cannot pass node-sets as parameters to the XSLT document.

Пример 4. Passing PHP variables to XSL files

<?php

// XML string
$xml = '<?xml version="1.0"?>
<para>
change me
</para>'
;

// XSL string
$xsl = '
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="ISO-8859-1" indent="no"
omit-xml-declaration="yes"  media-type="text/html"/>
<xsl:param name="myvar"/>
<xsl:param name="mynode"/>
<xsl:template match="/">
My PHP variable : <xsl:value-of select="$myvar"/><br />
My node set : <xsl:value-of select="$mynode"/>
</xsl:template>
</xsl:stylesheet>'
;


$xh = xslt_create ();

// the second parameter will be interpreted as a string
$parameters = array (
  
'myvar' => 'test' ,
  
'mynode' => '<foo>bar</foo>'
);

$arguments = array (
  
'/_xml' => $xml ,
  
'/_xsl' => $xsl
);

echo
xslt_process ( $xh , 'arg:/_xml' , 'arg:/_xsl' , NULL , $arguments , $parameters );

?>

Результат выполнения данного примера:

My PHP variable : test<br>
My node set : &lt;foo&gt;bar&lt;/foo&gt;

Замечание: Учтите, что в случае использования Windows, вам нужно указать file:// в начале пути.

Все функции PHP:
Авторизация
Логин

Пароль



Вы не зарегистрированы?
Нажмите здесь для регистрации.

Забыли пароль?
Запросите новый здесь.
Мини-чат
Вы должны авторизироваться, чтобы добавить сообщение.

12/04/2012 22:03
Это, в общем-то, нехороший признак

29/03/2012 18:52
Иногда хочется написать большими красными буквами, чтобы доходило быстрее Smile

29/03/2012 16:29
На форуме вопросы в основном ко мне, а я дальтоник

29/03/2012 15:31
Alipapa, а почему на форуме не включены цвета текста?

24/03/2012 18:38
Мультиблогом люди интересуются. Что имеется у нас?

02/03/2012 14:34
Как их запретить? Что-то в админке я не нашел, придется код править

23/02/2012 04:21
А ещё в голосованиях невозможно отредактировать опцию

23/02/2012 04:18
Alipapa, посмотри ГОЛОСОВАНИЯ НА ФОРУМЕ - почему у тебя там стоят по две кнопки "Обновить"?

23/02/2012 04:16
Желательно. Прилично.

21/02/2012 20:48
а это обязательно?

21/02/2012 19:23
Почему нет логотипа вверху на шапке? [img]http://ap-fus
ion.ru/images/news
_cats/ap-fusion.gi
f[/img]

13/02/2012 15:04
Всех влюблённых с праздником!!!

04/02/2012 09:08
Еще раз прошу всех. Если вопрос не личный, пишите в форум. В личке, аське, скайпе, мейле и т.д. не консультирую

14/01/2012 18:45
avisei, пиши в форум, а не шли мне личные посланья

31/12/2011 16:01
С праздником Нового Года! Успехов, счастья, богатства!

08/12/2011 16:13
MySQL нужен. Инструкция вот: [url]http://ap-fus
ion.ru/downloads.p
hp?download_id=58[
/url]

08/12/2011 16:03
Я канеш дико извиняюсь, но где на этом сайте статья по установке fusion, нужен ему MySql или нет? Smile

07/12/2011 11:03
ОК)

07/12/2011 11:02
этот - для 7.0

07/12/2011 11:00
Я устанавливаю, как в инструкции. Куча ошибок. Не могу сделать upgrade!

Анонс
Последние статьи
· О стабилизаторах нап...
· СМС и Вебмани
· TinyMCE для пользова...
· PCRE (Perl Compatibl...
· PCRE (Perl Compatibl...
4,796,720 уникальных посетителей Iceberg by Harly