For more info regarding encodings in SimpleXML and DOM, please visit http://www.onphp5.com/article/57
Funciones SimpleXML
Introducción
La extensión SimpleXML ofrece un conjunto de herramientas simples y fáciles de usar para convertir un XML en un objeto que puede ser procesado con selectores de propiedades e iteradores de matrices.
Requisitos
La extensión SimpleXML requiere PHP 5.
Instalación
La extensión SimpleXML está habilitada por defecto. Para deshabilitarla, usa la opción de configuración --disable-simplexml.
Ejemplos
Varios ejemplos de la referencia requieren una cadena XML. En vez de repetir esta cadena cada vez, la ponemos en un fichero php que incluiremos en cada ejemplo. éste fichero lo mostramos en la siguiente sección de ejemplo. Alternativamente, puedes crear un documento XML y cargarlo mediante la función simplexml_load_file().
Example#1 Fichero de Inclusión ejemplo.php con una cadena XML
<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El ActÓr</actor>
</character>
</characters>
<plot>
So, this language. It's like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
?>
La simplicidad de SimpleXML aparece más claramente cuando se extrae una cadena o un número de un documento XML básico.
Example#2 Obteniendo <plot>
<?php
include 'ejemplo.php';
$xml = simplexml_load_string($xmlstr);
echo $xml->movie[0]->plot; // "So this language. It's like..."
?>
Example#3 Accediendo a elementos no únicos en SimpleXML
Cuando existen multiples instancias de un elemento de un mismo elemento padre, se aplican las técnicas normales de iteración.
<?php
include 'ejemplo.php';
$xml = simplexml_load_string($xmlstr);
/* Para cada nodo <movie>, mostramos un <plot>. */
foreach ($xml->movie as $movie) {
echo $movie->plot, '<br />';
}
?>
Example#4 Usando atributos
Por ahora, solo hemos cubierto la parte de leer los nombres de los elementos y sus valores. SimpleXML también puede acceder a los atributos de los elementos. Acceder a los atributos de un elemento es como acceder a los elementos de una array.
<?php
include 'ejemplo.php';
$xml = simplexml_load_string($xmlstr);
/* Accede a los nodos <rating> de la primera película.
* Output the rating scale, too. */
foreach ($xml->movie[0]->rating as $rating) {
switch((string) $rating['type']) { // Obtenemos los atributos como elementos índice
case 'thumbs':
echo $rating, ' thumbs up';
break;
case 'stars':
echo $rating, ' stars';
break;
}
}
?>
Example#5 Comparando Elementos y Atributos con Texto
Para comparar un elemento o atributo con una cadena o pasarlo a una función que requiera una cadena, debes convertirlo a cadena mediante (string). De otra forma, PHP tratará el elemento como un objeto.
<?php
include 'ejemplo.php';
$xml = simplexml_load_string($xmlstr);
if ((string) $xml->movie->title == 'PHP: Behind the Parser') {
print 'Mi película favorita.';
}
htmlentities((string) $xml->movie->title);
?>
Example#6 Usando Xpath
SimpleXML incluye soporte nativo de Xpath. Para encontrar todos los elementos <character>:
<?php
include 'ejemplo.php';
$xml = simplexml_load_string($xmlstr);
foreach ($xml->xpath('//character') as $character) {
echo $character->name, 'played by ', $character->actor, '<br />';
}
?>
'//' sirve como comodín. Para especificar paths absolutos, hay que omitir una de las barras invertidas.
Example#7 Definiendo valores
Los datos en SimpleXML no tienen porqué ser constantes. El objeto permite la manipulación de todos sus elementos.
<?php
include 'ejemplo.php';
$xml = simplexml_load_string($xmlstr);
$xml->movie[0]->characters->character[0]->name = 'Miss Coder';
echo $xml->asXML();
?>
El código de arriba mostrará un documento XML nuevo, como el original, excepto que el nuevo XML tendrá Miss Coder en vez de Ms. Coder.
Example#8 Interoperabilidad con DOM
PHP tiene un mecanismo para convertir nodos XML entre los formatos de SimpleXML y DOM. Este ejemplo muestra como se podría cambiar un elemento DOM a otro SimpleXML.
<?php
$dom = new domDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Error al parsear el documento';
exit;
}
$s = simplexml_import_dom($dom);
echo $s->book[0]->title;
?>
Table of Contents
- SimpleXMLElement->addAttribute() — Adds an attribute to the SimpleXML element
- SimpleXMLElement->addChild() — Adds a child element to the XML node
- SimpleXMLElement->asXML — Devuelve una cadena XML basada en el objeto SimpleXML
- SimpleXMLElement->attributes — Identifica los atributos de un elemento
- SimpleXMLElement->children — Encuentra los hijos del nodo dado
- SimpleXMLElement->__construct() — Creates a new SimpleXMLElement object
- SimpleXMLElement->getDocNamespaces() — Returns namespaces declared in document
- SimpleXMLElement->getName() — Gets the name of the XML element
- SimpleXMLElement->getNamespaces() — Returns namespaces used in document
- SimpleXMLElement->registerXPathNamespace() — Creates a prefix/ns context for the next XPath query
- SimpleXMLElement->xpath — Ejecuta una petición Xpath en la cadena XML
- simplexml_import_dom — Obtiene un objeto SimpleXMLElement a partir de un nodo DOM.
- simplexml_load_file — Interpreta un fichero XML en un objeto
- simplexml_load_string — Interpreta una cadena XML en un objeto
SimpleXML
19-Nov-2007 04:49
18-Nov-2007 02:37
It does not say in the docs, but SimpleXML will convert all text into UTF-8, if the source XML declaration has another encoding. Eg, if the source has the following XML decl:
<?xml version="1.0" encoding="windows-1251" ?>
all the text in the resulting SimpleXMLElement will be in UTF-8 automatically.
09-Nov-2007 04:14
If you want to compare two XML documents for loose equality -- i.e. they both have the same attributes, children and text content, over all namespaces -- then you can use the function provided below.
I don't know of any easier way to do this -- it would make sense to be part of the SimpleXML extension, I'm sure.
<?php
$xml1 = new SimpleXMLElement(file_get_contents('file1.xml'));
$xml2 = new SimpleXMLElement(file_get_contents('file2.xml'));
$result = xml_is_equal($xml1, $xml2);
if ($result === true) {
// the XML documents are the same
} else {
// they are different: print the reason why
printf(STDERR, "XML documents are different: $result");
}
?>
xml_is_equal() source: http://www.jevon.org/wiki/Comparing_Two_SimpleXML_Documents
31-Oct-2007 05:32
This function could be useful to somebody if you want to insert an XML into another when building an XML from many different files.
Note that you must specify a name for the node in which the child files content/node will be inserted :
foreach (xxx as $firstCondition){
$xml_parent = simplexml_load_file("$firstCondition.xml");
foreach (yyy as $secondCondition){
$xml_children = simplexml_load_file("secondCondition.xml");
SimpleXMLElementObj_into_xml($xml_parent , $xml_children , 'linkingNode'); //will insert every nodes of the files at the end of the parent_xml
} }
function SimpleXMLElementObj_into_xml($xml_parent, $xml_children, $linkingNode= "linkingNode" , $child_count = 0 , $xml = false ){
if(!$xml) {
$xml = $xml_parent->addChild($linkingNode);
}else{
$xml = $xml_parent[$child_count];
}
$child_count = 0;
foreach($xml_children->children() as $k => $v) {
if($xml->$k){
$child_count++;
}
if($v->children()) {
$xml->addChild($k);
SimpleXMLElementObj_into_xml($xml->$k, $v, '', $child_count, true);
}else{
$xml->addChild($k, $v);
}
}
return $xml;
}
Thanks to some contributor whom I've taken the structure of this function.
23-Oct-2007 02:35
If you need to do math calculations on values extracted from simplexml document, you might need to cast the value as float to prevent precision loss. Here is an example:
<?
$objXML = new SimpleXMLElement('<test x="-123.45"></test>');
//Shows correctly
echo $objXML['x']."\n";
//We loose the decimals
echo $objXML['x'] + $objXML['x']."\n";
$x = $objXML['x'];
//This works if we cast the amounts
echo (float)$objXML['x'] + (float)$objXML['x']."\n";
//Calculated on a string, no problem
echo "-123.45" + "-123.45";
?>
This is due to the fact that $objXML['x'] is not a string (php would cast it automatically) neither a float, but a SimpleXMLElement object.
"echo var_dump($x);" will output this
~~
object(SimpleXMLElement)#3 (1) {
[0]=>
string(7) "-123.45"
}
~~
I opened a bug request on php but here is the answer they gave me:
~~
Status: Won't fix
The behavior is defined by the engine not the extension. When performing mathematical operations on objects, they are treated as integers. It is up to the user to cast the object to the appropriate type to maintain proper precision.
~~
29-Aug-2007 04:04
@Leonid Kogan:
Your script is not working in all cases. It has problem with non-uniques elements, ie:
<?php $array = array( 'root' => array( 'first' => array( 'value', 'other' ) ) );?>
In XML it should looks like this:
<root>
<first>value</first>
<first>other</first>
</root>
But it will looks:
<root>
<first>
<1>value</1>
<2>other</2>
</first>
</root>
which is wrong.
27-Aug-2007 03:07
I had a problem with entities.
My first solution:
I saved Data that way:
$ENTRY_->
addchild('Nachricht',htmlentities($_POST["blog"]));
Had Entities in the XML-File like:
<!ENTITY auml "&auml">
And I loaded the Data that way:
html_entity_decode($ENTRY->Nachname);
But after saving and
loading the xml-file the entity-entry
<!ENTITY auml "&auml">
disappeared. strange...
My second solution:
With saving the Data this way:
$ENTRY_->
addchild('Nachricht',htmlentities(htmlentities($_POST["blog"])));
I can now load it with html_entity_decode without the
entity-entry in the XML-file!
I tested it with äöü.
Hope it helpes.
26-Aug-2007 05:29
You dont need a function named "fixCDATA".
Work with "htmlentities" and "html_entity_decode" is
better.
A short example:
$xml->addChild($key, "<![CDATA[".htmlentities($value)."]]>");
print_r((html_entity_decode($files_xml->asXML())));
Greetings S.P. aka darki777
22-Aug-2007 05:40
You can't use CDATA with SimpleXML, but there is a way around it. Wrap your child in CDATA like this:
<? $listing->addChild( 'description', '<![CDATA[' . $row['description'] . ']]>' ); ?>
And then when you display the XML, run it through this function:
<?
function fixCDATA($string) {
$find[] = '<![CDATA[';
$replace[] = '<![CDATA[';
$find[] = ']]>';
$replace[] = ']]>';
return $string = str_replace($find, $replace, $string);
}
$xml = fixCDATA( $xml->asXML() );
echo $xml;
?>
16-Aug-2007 06:28
When creating a new XML document and adding text with umlauts and such
$SimpleXMLElement->asXML();
will silently NOT output any content with umlauts.
Use htmlentities () while adding Umlauts & co to solve the "problem"
16-Aug-2007 12:10
if you want to export an array as xml you can use this script
<?php
$test=array("TEST"=>"nurso",
"none"=>null,
"a"=>"b",
array(
"c"=>"d",
array("d"=>"e")));
$xml=array_to_simplexml($test);
print->($xml);
print_r($xml->asXML());
function array_to_simplexml($array, $name="config" ,&$xml=null )
{
if(is_null($xml))
{
$xml = new SimpleXMLElement("<{$name}/>");
}
foreach($array as $key => $value)
{
if(is_array($value))
{
$xml->addChild($key);
array_to_simplexml($value, $name, $xml->$key);
}
else
{
$xml->addChild($key, $value);
}
}
return $xml;
}
?>
04-Aug-2007 05:40
If you're handling lots of HTML or mixed-content XML you'll probably want to use the DOM functions instead of SimpleXML. Take this for example:
<?php
$html = new SimpleXMLElement('<div><p>Some text, <a href="#">a link,</a> more text</p></div>');
echo $html->p->a,"<br>\n"; // "a link,"
echo $html->p; // "Some text, more text" (!)
?>
In the above example reconstructing the original markup is impossible because of the way SimpleXML represents the data.
04-Aug-2007 03:49
For the poor users who can only use a PHP4 solution, there are some alternatives to it like minixml or my simple php class called sxml which runs with php5 as well as with php4: http://www.shop24-7.info/32-0-simplexml-alternative-php4.html
It is easy to modify and has a clear structure. The result of the class is an array which owns the xml file's data.
have fun with it
24-Jul-2007 05:41
When using Apache & PHP on windows and you try to do a direct typecast to string or integer of your SimpleXMLElement objects, your Apache MAY crash (mine did :-( ).
would look like this:
$id = (int)$xml->id;
so try other things like firts converting it to a string with strval() NOT direct typecast - this won't work neither.
seems like direct typecast doesnt work on objects (doesn' suprise me very much)
19-Jul-2007 01:45
<to bens at effortlessis dot com>
I see your problem, but there's a workaround.
After loading your SimpleXML object into $xml, call $xml->getName () and you'll get your root tag name.
I use PHP 5.1.4 on Apache 1.3.33 on MacOS X and this works on it. I hope there was no SimpleXML ability downgrading :o)
Also, I kinda remember reading somewhere in this doc an advise saying "Don't use data structures parsers like var_dump() on SimpleXML." This may be the reason. And you may will work your second problem around using SimpleXMLElement->attributes() and SimpleXMLElement->getName ().
18-Jul-2007 11:58
Data can be lost when using SimpleXML!!! Consider the following XML:
<root position="base">
<edition id="20070705" onsale="2007-07-06" online="2007-07-06 09:00">
<headline maxchars="50" someattr="whatever">
<cell attr="meaningless">The new issue</cell>
</headline>
</edition>
<monkey id="123">
<face class="round">red</face>
<face class="square">pink</face>
</monkey>
</root>
parsed as follows
$res = simplexml_load_string($xml);
print_r($res);
1) The name of the first (root?) tag of the document is lost - there is no way to find out what the root tag was called. (in this case, I called it "root") However, the attributes within that tag are preserved. (position="base")
2) The innermost tag's attributes are lost. (apparently, any tag with data in it) Note that attr='meaningless' in the cell tag, as well as the class="square"/"round" is lost.
This is when using PHP 5.1.6 on Fedora Core 6 with stock RPMs.
05-Jul-2007 04:23
Correct me if I'm wrong, but I think the output of the SimpleXMLElement Object is dependent on the PHP version. Consider this code:
$xml = '<edition id="20070705" onsale="2007-07-06" online="2007-07-06 09:00">
<headline maxchars="50">The new issue</headline>
</edition>';
$res = simplexml_load_string($xml);
print("<pre>");
print_r($res);
print("</pre>");
PHP version 5.0.4 will return this:
SimpleXMLElement Object
(
[headline] => The new issue
)
While PHP version 5.2.1 returns (some) attributes as well:
SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 20070705
[onsale] => 2007-07-06
[online] => 2007-07-06 09:00
)
[headline] => The new issue
)
16-Jun-2007 07:27
In response to webmaster at mavoric dot net comment.
It is a complete non-sense to use include() to retrieve an external RSS feed, remember that include is intented to **parse and execute PHP code** and an RSS feed is, quite obivously, **not** PHP code.
people that wants to read external resources should use file_get_contents, fopen or an SplFileObject, never **ever** use include() with remote resources.
05-Jun-2007 06:26
If you are using the above examples to get at external XML/RSS files and are encountering errors, you need to understand that PHP Version 5.2.3 + forbids the use of using include to get at external XML/RSS files . You need to change the start of the code slightly...
<?php
$url = 'http://www.a_external_site.com/example.xml';
$rss_file = file_get_contents($url);
$xml = new SimpleXMLElement($rss_file);
echo $xml->movie[0]->plot; // "So this language. It's like..."
?>
Just replace the first two lines of the exsisting code with the first two of the above code.
30-Apr-2007 12:55
I've implemented a XML Pull Parser for PHP 5 that somewhat mimics SimpleXML - but doesn't need to load the whole document in memory :
http://tinyurl.com/2e9ew5
09-Apr-2007 03:14
It is a grave misfortune that this doesn't work:
<?
$node = new SimpleXml;
echo $node->{"namespace:tagname"}[attribute'];
?>
Instead you have to go through loops!
<?
$namespace = $node->children( 'namespace' );
$attributes = $namespace->tagname->attributes;
echo $attribute['attribute'];
?>
AFAICT there is no simpler way. SimpleXml is great in premise, but useless for things like RSS feeds, which lets face it, most PHP development with XML is about.
Great shame!
29-Mar-2007 11:13
Making SimpleXMLElement objects session save.
Besides the effect of not surviving sessions, the SimpleXMLElement object may even crash the session_start() function when trying to re-enter the session!
To come up with a solution for this, I used a pattern as follows. The core idea is to transform the SimpleXMLElement between session calls to and from a string representation which of course is session save.
<?php
//
// session save handling of SimpleXMLElement objects
// (applies to/ tested with PHP 5.1.5 and PHP 5.2.1)
// The myClass pattern allows for conveniently accessing
// XML structures while being session save
//
class myClass
{
private $o_XMLconfig = null;
private $s_XMLconfig = '';
public function __construct($args_configfile)
{
$this->o_XMLconfig = simplexml_load_file($args_configfile);
$this->s_XMLconfig = $this->o_XMLconfig->asXML();
} // __construct()
public function __destruct()
{
$this->s_XMLconfig = $this->o_XMLconfig->asXML();
unset($this->o_XMLconfig); // this object would otherwise crash
// the subsequent call of
// session_start()!
} // __destruct()
public function __wakeup()
{
$this->o_XMLconfig = simplexml_load_string($this->s_XMLconfig);
} // __wakeup()
} // class myClass
?>
28-Mar-2007 04:03
Concerning SimpleXML and sessions:
When creating a SimpleXML object (to be precise: a SimpleXMLElement object) in the context of a session and storing it in $_SESSION['XMLobject'], this object does not "survive" the session!
By the time re-entering the session, print_r($_SESSION['XMLobject']) says:
['XMLobject'] => SimpleXMLElement Object
Warning: Node no longer exists in /your_php_file.php on line xyz
(
)
(Message simplified for the sake of better readability.)
11-Mar-2007 11:46
Sometimes it's nice to mix up data storage types. This is a very simple SQL to XML converter. Feed it a SQL query and it outputs the result in XML.
The first paramater should be a mysql_query result
(optional)The second is the xml name for each row (i.e the second depth of XML)
(optional)The third is the name of the XML document, the root name
<?php
$result=mysql_query("SELECT * FROM users");
sql_to_xml($result,"users","members");
function sql_to_xml($mysql_result,$row_name="row",$doc_name="root")
{
$xml= new SimpleXMLElement("<$doc_name></$doc_name>");
while($line=mysql_fetch_assoc($mysql_result))
{
$row=$xml->addChild($row_name);
foreach($line as $column => $value)
{
$row->$column="$value";
}
}
return $xml->asXML();
}
?>
22-Feb-2007 12:04
Memory leak when setting attributes as in example (#Example 2134. Setting values)
This probably goes unnoticed in web scripts (unless you do a LOT of xml manipulations), but I ran into this in my standalone script that processes a large number of XML files.
The following code will eat up memory quite fast:
<?php
include 'example.php';
while (true) {
$xml = new SimpleXMLElement($xmlstr);
$xml->movie[0]->characters->character[0]->name = 'Miss Coder';
}
?>
while this seems to behave correctly:
<?php
include 'example.php';
while (true) {
$xml = new SimpleXMLElement($xmlstr);
$c = $xml->xpath("//character");
$c[0]->name = 'Miss Coder';
}
?>
This looks like bug #38604, and I just confirmed that in 6.0.0-dev (on Windows at least) it is fixed. It is NOT fixed in 5.2.1 or 5.2.2-dev (2/21 build), so for 5.2 users, use the second form to avoid leaks.
20-Feb-2007 03:57
It doesn't mention this anywhere, but creationg a new SimpleXMLElement object from a non-valid string throws an exception. It looks ugly in the php log as it dumps the stack in multiple lines.
The correct way to create a new SimpleXMLElement object is like so:
<?php
$xmlstr = ''; // empty to throw an exception
try {
$xml = new SimpleXMLElement($xmlstr);
} catch (Exception $e) {
// handle the error
echo '$xmlstr is not a valid xml string';
}
?>
13-Dec-2006 05:10
One way to work around the issue that Arnaud presented on 19-Oct-2006 is to check for the existence of the node before doing a 'foreach' on it.
<?php
$xml = simplexml_load_string('<root></root>');
if( $xml->b ) // Or maybe 'isset' or 'array_key_exists'
{
foreach($xml->b as $dummy);
}
echo $xml->asXML();
?>
Gives the expected result:
<?xml version="1.0"?>
<root/>
You can see the same behavior using an array, although you'll get a warning:
<?php
$p['a'] = '1';
foreach( $p['b'] as $node );
print_r( $p );
?>
Result:
Warning: Invalid argument supplied for foreach()
Array
(
[a] => 1
[b] =>
)
06-Nov-2006 09:40
Be careful when using var_export to debug element attributes - it won't work! Always use print() or similar for checking the contents of element attributes.
19-Oct-2006 04:35
As of PHP 5.1.4, trying to iterate on a non-existent node will actually create that node.
<?
$xml = simplexml_load_string('<root></root>');
foreach($xml->b as $dummy);
echo $xml->asXML();
?>
Gives :
<?xml version="1.0"?>
<root><b/></root>
You might think it is a bug, but PHP developers seam to consider it as a feature : http://bugs.php.net/bug.php?id=39164
16-Oct-2006 06:15
simplexml provides a neat way to do 'ini' files. Preferences for any number of users can be held in a single XML file having elements for each user name with user specific preferences as attributes of child elements. The separate <pref/>'s could of course be combined as multiple attributes of a single <pref/> element but this could get unwieldy.
In the sample code below the makeXML() function uses the simplexml_load_string function to generate some XML to play with and the readPrefs() function parses the requested users preferences into an array.
<?
function makeXML() {
$xmlString = <<<XML
<preferences>
<johndoe>
<pref color="#FFFFFF"/>
<pref size="14"/>
<pref font="Verdana"/>
</johndoe>
<janedoe>
<pref color="#000000"/>
<pref size="16"/>
<pref font="Georgia"/>
</janedoe>
</preferences>
XML;
return simplexml_load_string($xmlString);
}
function readPrefs($user, $xml) {
foreach($xml->$user as $arr);
$n = count($arr);
for($i=0;$i<$n;$i++) {
foreach($xml->$user->pref[$i]->attributes() as $a=>$b) {
$prefs[$a] = (string)$b;
}
}
print_r($prefs);
}
readPrefs('johndoe', makeXML());
?>
28-Aug-2006 12:31
to eho when using name space you need to select the arry from it (xpath turns all of it in to array)
<?php
$logined = $xml->xpath('/root/login/@status');
echo $logined[0];
//to see the the array its self
//use print_r() function
//
print_r($logined);
?>
20-Jul-2006 10:41
Just a minor modification to Daniel Favire's simplexml2ISOarray function: I added an if-block around the attributes section so you don't get a SimpleXML attributes element along with each attributes array:
function simplexml2ISOarray($xml,$attribsAsElements=0) {
if (get_class($xml) == 'SimpleXMLElement') {
$attributes = $xml->attributes();
foreach($attributes as $k=>$v) {
if ($v) $a[$k] = (string) $v;
}
$x = $xml;
$xml = get_object_vars($xml);
}
if (is_array($xml)) {
if (count($xml) == 0) return (string) $x; // for CDATA
foreach($xml as $key=>$value) {
$r[$key] = simplexml2ISOarray($value,$attribsAsElements);
if (!is_array($r[$key])) $r[$key] = utf8_decode($r[$key]);
}
if (isset($a)) {
if($attribsAsElements) {
$r = array_merge($a,$r);
} else {
$r['@'] = $a; // Attributes
}
}
return $r;
}
return (string) $xml;
}
09-Jul-2006 09:29
"When parsing and processing an instance document, SimpleXML is an excellent technology choice. However, if significant manipulation is required, it is important that the technology understands the model for the document, and in that case, SDO [see http://php.net/sdo ] is probably a more appropriate choice."
(Charters, Peters, Maynard and Srinivas from http://www.zend.com/pecl/tutorials/sdo.php )
31-May-2006 08:31
Here is my Simple XML to array function, it is recursive and has the benefit of maintaining key value relationships and has worked well for me.
function XMLToArray($xml)
{
if ($xml instanceof SimpleXMLElement) {
$children = $xml->children();
$return = null;
}
foreach ($children as $element => $value) {
if ($value instanceof SimpleXMLElement) {
$values = (array)$value->children();
if (count($values) > 0) {
$return[$element] = XMLToArray($value);
} else {
if (!isset($return[$element])) {
$return[$element] = (string)$value;
} else {
if (!is_array($return[$element])) {
$return[$element] = array($return[$element], (string)$value);
} else {
$return[$element][] = (string)$value;
}
}
}
}
}
if (is_array($return)) {
return $return;
} else {
return $false;
}
}
20-May-2006 09:42
I've written a tutorial demonstating how to update a Google sitemap dynamically using the PHP5 SimpleXML extension.
http://www.phpfive.net/article34.htm
18-May-2006 04:21
SimpleXML handles namespaces, but it's not documented very well here at all.
If you wanted to parse, say, an open office manifest file or a piece of RDF/XML, you have to get elements and attributes by the namespace url.
Example:
<?php
function display($in) {
if (file_exists($in)) {
$xml = simplexml_load_file($in);
} else {
throw new Exception($in . " does not exist");
}
$manifest = $xml->children('http://openoffice.org/2001/manifest');
foreach ($manifest->xpath('//manifest:file-entry') as $file) {
foreach ($file->attributes('http://openoffice.org/2001/manifest') as $key => $value) {
print "Key:" . $key . "\n";
print "Value:" . $value . "\n";
}
}
}
?>
File: manifest.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE manifest:manifest PUBLIC "-//OpenOffice.org//DTD Manifest 1.0//EN" "Manifest.dtd">
<manifest:manifest xmlns:manifest="http://openoffice.org/2001/manifest">
<manifest:file-entry manifest:media-type="application/vnd.sun.xml.writer" manifest:full-path="/"/>
<manifest:file-entry manifest:media-type="application/vnd.sun.xml.ui.configuration" manifest:full-path="Configurations2/"/>
<manifest:file-entry manifest:media-type="application/binary" manifest:full-path="layout-cache"/>
<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="content.xml"/>
<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="styles.xml"/>
<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="meta.xml"/>
<manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/thumbnail.png"/>
<manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/"/>
<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="settings.xml"/>
</manifest:manifest>
05-May-2006 10:11
More new stuff.
<?php
$xml = "
<test></test>
";
$xml = simplexml_load_string($xml);
$xml->addChild('new','value','namespace');
echo $xml->asXml();
?>
output:
<?xml version="1.0"?>
<test><new xmlns="namespace">value</new></test>
Very nice and clean. DOM is so awkward compared to this.
02-May-2006 08:04
This is one new stuff to get the root name (since PHP 5.1.3) :
<?php
$xml = simplexml_load_string( '<foo name="bar" />' );
echo $xml->getName(); // displays foo
?>
07-Sep-2005 10:51
While you can't add new elements to a SimpleXML object you can however add new attributes
<?php
$string = '<doc channel="chat"><test1>Hello</test1></doc>';
$xml = simplexml_load_string($string);
$xml->test1['sub'] = 'No';
echo $xml->asXML();
?>
Will return output
<doc channel="chat"><test1 sub="No">Hello</test1></doc>
03-Sep-2005 05:52
I tried extending SimpleXMLElement to add some functionality and found you can't set new properties. I assume this is something to do with built-in magic methods or something.
So I wrote a class that behaves the same as SimpleXMLElement (by delegating most of it's work) but is arbitrarily extendable.
http://www.oliverbrown.me.uk/2005/09/03/extending-simplexml/
It's very new and not very well tested but could be useful to somebody.
08-Jun-2005 03:07
after wondering around some time, i just realized something (maybe obvious, not very much for me). Hope helps someone to not waste time as i did :-P
when you have something like:
$xmlstr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<double xmlns="http://foosite.foo/">2328</double>
XML;
you will have the simpleXML object "transformed" to the text() content:
$xml = simplexml_load_string($xmlstr);
echo $xml; // this will echo 2328 (string)
06-May-2005 03:11
Hi,
If you want to access an element that has a dash in its name, (as is common with the XML documents provided by the Library of Congress, as well as the NWS) you will need to handle it a little bit differently.
You can either use XPATH, which works fine, but will return an array of results every time, even if there is a single result.
eg.
$xml->xpath('/data/time-layout/start-valid-time'}
You can also choose just to encapsulate the element names containing a dash:
$xml->data->{'time-layout'}->{'start-valid-time'}
--
On a only partially related note, dealing with SimpleXML is one of the only times I have employed casting with PHP. While iterating (foreach) through the valid times, echo'ing the element worked great (it merely echo'ed the apropriate time), assigning it to another variable resulted in a SimpleXML object containing the time to be assigned, rather than just the time itself. This was resolved by casting the time to a string:
foreach($xml->data->{'time-layout'}->{'start-valid-time'} AS $time)
{
$weatherDates[] = (string) $time;
}
04-May-2005 11:57
Another method to parse an XML Document into a PHP array with SIMPLEXML inspired from Daniel FAIVRE !
function xml2php($xml)
{
$fils = 0;
$tab = false;
$array = array();
foreach($xml->children() as $key => $value)
{
$child = xml2php($value);
//To deal with the attributes
foreach($node->attributes() as $ak=>$av)
{
$child[$ak] = (string)$av;
}
//Let see if the new child is not in the array
if($tab==false && in_array($key,array_keys($array)))
{
//If this element is already in the array we will create an indexed array
$tmp = $array[$key];
$array[$key] = NULL;
$array[$key][] = $tmp;
$array[$key][] = $child;
$tab = true;
}
elseif($tab == true)
{
//Add an element in an existing array
$array[$key][] = $child;
}
else
{
//Add a simple element
$array[$key] = $child;
}
$fils++;
}
if($fils==0)
{
return (string)$xml;
}
return $array;
}
01-Mar-2005 03:05
Note that SimpleXML expects to both read and output XML in UTF-8 encoding. You'll need to add a line such as this at the top of your input XML file if it isn't saved in UTF-8 (adjust to whatever encoding used):
<?xml version="1.0" encoding="ISO-8859-1" ?>
On the output side of things, if you're not serving/handling UTF-8, you'll need to use utf8_decode() [red. but that will only work for ISO-8859-1, not other encodings]. Common mistake: http://bugs.php.net/bug.php?id=28154
07-Jan-2005 08:37
A simple way to merge two SimpleXML objects.
<?php
/**
* Pumps all child elements of second SimpleXML object into first one.
*
* @param object $xml1 SimpleXML object
* @param object $xml2 SimpleXML object
* @return void
*/
function simplexml_merge (SimpleXMLElement &$xml1, SimpleXMLElement $xml2)
{
// convert SimpleXML objects into DOM ones
$dom1 = new DomDocument();
$dom2 = new DomDocument();
$dom1->loadXML($xml1->asXML());
$dom2->loadXML($xml2->asXML());
// pull all child elements of second XML
$xpath = new domXPath($dom2);
$xpathQuery = $xpath->query('/*/*');
for ($i = 0; $i < $xpathQuery->length; $i++)
{
// and pump them into first one
$dom1->documentElement->appendChild(
$dom1->importNode($xpathQuery->item($i), true));
}
$xml1 = simplexml_import_dom($dom1);
}
$xml1 = simplexml_load_string('<root><child>child 1</child></root>');
$xml2 = simplexml_load_string('<root><child>child 2</child></root>');
simplexml_merge($xml1, $xml2);
echo($xml1->asXml());
?>
Will output:
<?xml version="1.0"?>
<root>
<child>child 1</child>
<child>child 2</child>
</root>
03-Jan-2005 07:18
If you are looking to use SimpleXML for anything but reading XML documents, you should really reconsider, and use the XML DOM library. By the time you get enough utilities implemented in DOM to handle all the set backs in SimpleXML, you will have defeated the purpose of using SimpleXML. There are a few reasons for this, and there are already many workrounds, but the primairy issues are this
1) No complex node assignment. You cannot switch nodes or replace them.
2) No appending new child nodes
3) Whenever you do something like $new_node = $xml_doc->node you will always get a reference even if you use a clone method, which will crash the script.
Other than that, its a great tool for reading docs.
01-Sep-2004 02:11
simplexml does not simply handle CDATA sections in a foreach loop.
<?php
$sx = simplexml_load_string('
<test>
<one>hi</one>
<two><![CDATA[stuff]]></two>
<t>
<for>two</for>
</t>
<multi>one</multi>
<multi>two</multi>
</test>');
foreach((array) $sx as $tagname => $val) {
if (is_string($val)) {
// <one> will go here
} elseif (is_array($val)) {
// <multi> will go here because it happens multiple times
} elseif (is_object($val)) {
// <t> will go here because it contains tags
// <two> will go here because it contains CDATA!
}
}
?>
To test in the loop, do this
<?php
if (count((array) $val) == 0) {
// this is not a tag that contains other tags
$val = '' . $val;
// now the CDATA is revealed magically.
}
?>
18-Jun-2004 01:58
A introductory tutorial on simplexml can be found here:
* http://www.zend.com/php5/articles/php5-simplexml.php
* http://www.zend.com/php5/abs/php101-11.php
* http://www.onlamp.com/pub/a/php/2004/01/15/simplexml.html
20-Feb-2004 01:04
Simplexml's simplicity can be deceptive. Simplexml elements behave either as objects or strings, depending on the context in which they're used (through overloading of the __toString() method, I assume). Statements implying conversion to string treat them as strings, while assignment operations treat them as objects. This can lead to unexpected behavior if, for example, you are trying to compare the values of two Simplexml elements. The expected syntax will not work. To force conversion to strings, just "typecast' whatever Simplexml element you're using. For example:
<?php
$s = simplexml_load_string('<foo>43</foo> <bar>43</bar>');
// Evaluates to false by comparing object IDs instead of strings
($s->foo == $s->bar);
// Evaluates to true
((string)$s->foo == (string)$s->bar);
?>
[Ed. Note: Changed from quotes to casts because casts provide a quicker and more explicit conversion than do double quotes.]
