downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

wddx_add_vars> <w32api_set_call_method
[edit] Last updated: Mon, 01 Nov 2010

view this page in

CLXVI. Funções WDDX

Introdução

Essas funções tem o intuito de funcionara com WDDX.

Dependências

Para usar WDDX, você precisará instalar a biblioteca expat (que vem com o Apache 1.3.7 ou superior).

Instalação

Depois de instalar o expat, compile o PHP com a opção --enable-wddx.

A versão para Windows do PHP tem suporte embutido para esta extensão. Você não precisa carregar nenhuma extensão adicional para utilizar essas funções.

Configurações em execução

Esta extensão não define nenhum parâmetro de configuração no php.ini.

Tipos Resource

Esta extensão não possui nenhum tipo resource.

Constantes pré-definidas

Esta extensão não possui nenhuma constante.

Exemplos

Todas as funções que serializam variáveis usam o primeiro elemento de um array para determinar se o array deve ser serializado em um array ou estrutura. Se o primeiro elemento tem uma chave string, então ele é serializado em uma estrutura, caso contrário, em um array.

Exemplo 1. Serializando um único valor com WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

Esse exemplo produzirá:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Exemplo 2. Usando pacotes incrementais com WDDX

<?php
$pi
= 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo
$packet;
?>

Esse exemplo produzirá:

<wddxPacket version='1.0'><header comment='PHP'/><data><struct>
<var name='pi'><number>3.1415926</number></var><var name='cities'>
<array length='3'><string>Austin</string><string>Novato</string>
<string>Seattle</string></array></var></struct></data></wddxPacket>

Nota: Se você quiser serializar caracteres não-ASCII, você tem que primeiro converter seus dados para UTF-8 (veja utf8_encode() e iconv()).

Índice
wddx_add_vars --  Adiciona variáveis a um pacote WDDX com o IP especificado
wddx_deserialize -- Sinônimo de wddx_unserialize()
wddx_packet_end -- Finaliza um pacote WDDX com o ID especificado
wddx_packet_start --  Inicializa um novo pacote WDDX com uma estrutura dentro dele
wddx_serialize_value -- Serializa um único valor em um pacote WDDX
wddx_serialize_vars -- Serializa variáveis em um pacote WDDX
wddx_unserialize -- De-serializa um pacote WDDX


wddx_add_vars> <w32api_set_call_method
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes Funções WDDX
iGEL 14-Mar-2008 02:03
As of version 5.2.5, this is wrong:

> Note: If you want to serialize non-ASCII characters you
> have to convert your data to UTF-8 first (see utf8_encode()
> and iconv()).

Serializing a string with WDDX will always convert it from ISO-8859-1 to UTF-8, no matter what the original encoding is. So if your data already are UTF-8, you get just gibberish.

You can restore the original encoding by using utf8_decode on the serialized wddx data, even though your original data may use chars not included in ISO-8859-1:

<?php
header
("Content-Type: text/xml;encoding=utf-8");
echo
utf8_decode(wddx_serialize_value("안녕 하세요"));
?>

(This is why I dislike PHP, sorry)
egbert teeselink 23-Feb-2008 10:50
I'm horrible, forgot to include a helper function:

function getchild($node)
{
    if(count($node) > 1) echo "warning: node $node has more than 1 child";
    foreach($node->children() as $name => $subnode) {}
    return array($subnode, $name);
}
egbert teeselink 23-Feb-2008 10:49
If your PHP doesn't have wddx support installed, and you need it, and you don't want to install PEAR just for wddx, try this short piece of code, based on SimpleXML:

//can read any wddx file generated from php arrays. assumes var elements are only inside struct elements and that only one packet exists.
function wddx_read_node($node, $type)
{
    switch($type)
    {
    case "boolean":
        return (string)$node;
    case "number":
    case "binary":
    case "string":
        return (string)$node;
    case "null":
        return null;
    case "array":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            $a[] = wddx_read_node($subnode, $subtype);
        }
        return $a;
    case "struct":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            list($key, $value) = wddx_read_node($subnode, $subtype); //must be a var element
            $a[$key] = $value;
        }
        return $a;
    case "var":
        list($subnode, $subtype) = getchild($node);
        return array((string)$node["name"], wddx_read_node($subnode, $subtype));
    case "data":
        list($subnode, $subtype) = getchild($node);
        return wddx_read_node($subnode, $subtype);
    }
}

function wddx_read($string)
{
    $xml = simplexml_load_string($string);
    $d = wddx_read_node($xml->data, "data");
    return $d;
}

important notice: this one may not work with all wddx input. multiple packets or variables outside a "struct" are not supported. basically, you always get a PHP (associative) array, never something else. feel free to make additions.
no at spam dot thx 12-Aug-2007 02:09
To bradburn at kiwi dot de:

PHP is only capable of serializing properly variables which match one of its native (scalar) types (See http://php.net/types). Which means that only variables of type booleans, integers, floating point numbers, string and NULL will be serialized properly.

I think there are two exceptions though:
- arrays are serialized by processing them recursively, so if its only composed of the above mentioned types, you should be fine.
- floating point numbers and integers may use the same representation while serialized in WDDX (I don't know much about WDDX, so I'm not 100% sure about this statement).

An interesting case would be whether objects can be serialized or not...
Jimmy Wimenta 15-Jul-2004 05:53
PHP's WDDX is useful only for exchanging data between PHP applications, but definetly not for exchanging data between different languages (which actually defeats the purpose of WDDX).

For example:

$hash1 = array ("2" => "Two", "4" => "Four", "5" => "Five");
$hash2 = array ("0" => "Zero", "1" => "One", "2" => "Two");

$hash1 will be serialized as hash, but
$hash2 will be serialized as array/list, because the key happen to be a sequence starting from 0.

Unless the library provide a way for users to specify the type, it can never be used for cross-platform data exchange.
Q1tum at hotmail dot com 21-Nov-2003 05:08
To insert arrays into a wddx variable here is a fine way to do it:

<?php

$sql
= 'SELECT * FROM example';
$query = mysql_query($sql, $db) or die(mysql_error());

while(
$result = mysql_fetch_array($query)) {
   
$id[] = $result[ 'id'];
   
$name[] = $result['name'];
   
$description[] = $result[$prefix . 'description'];
}

mysql_free_result($query);

wddx_add_vars($packet_id, "id");
wddx_add_vars($packet_id, "name");
wddx_add_vars($packet_id, "description");

$wddxSerializeValue = wddx_packet_end($packet_id);

?>
11-Sep-2003 07:29
wddx isn't 100% perl compatible .. I have an wddx file infront of me and it only works with php so better don't use it
bradburn at kiwi dot de 30-Jul-2002 07:02
With ref to the above comment about typing, I have found that -- oddly enough -- PHP's WDDX supports the following WDDX types: null, boolean (true/false), number and string, *but* not date-time.

as an example, use the following values in an array that you then serialize:

$number = 5,
$null = NULL,
$bool = true,
$string = 'this is a string'.

they will all serialize correctly, e.g. the third entry comes out as:

<var name='bool'><boolean value='true'/></var>

i have tried with the 'official' format for WDDX 'datetime', e.g. '1998-9-15T09:05:32+4:0' (from the DTD @ http://www.openwddx.org/downloads/dtd/wddx_dtd_10.txt)  but have only succeeded in getting this encoded as a 'string' type.

if anyone else has any more information on this, it would be welcome. i would like to store the variables in 'appropriate' fields in a database, and the fact that only datetime is not supported is slightly irritating -- otherwise it would be a very useful function.
djm at web dot us dot uu dot net 18-Oct-1999 08:45
Since there aren't any examples of reversing the process, here's one. If you had the packet produced by the above example (without the htmlentities() call), you could retrieve the values like this:

<?php
$value
= wddx_deserialize($packet);
print
"pi is:<br>" . $value["pi"] . "<p>\n";
print
"cities is:<br>\n";
while (list(
$key, $val) = each($value["cities"])) {
    print
"$key => $val<br>\n";
}
?>

which outputs:

<pre>
pi is:
3.1415926

cities is:
0 => Austin
1 => Novato
2 => Seattle
</pre>

 
show source | credits | sitemap | contact | advertising | mirror sites