ScotlandPHP

SimpleXML

add a note add a note

User Contributed Notes 30 notes

up
213
soloman at textgrid dot com
6 years ago
Three line xml2array:

<?php

$xml
= simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

?>

Ta da!
up
5
bxt at die-optimisten dot net
8 years ago
Addition to QLeap's post:
SimpleXML will return a reference to an object containing the node value and you can't use references in session variables as there is no feasible way to restore a reference to another variable.

This won't work too:
$val=$this->xml->node->attributes()->name;
echo $array[$val]; // will cause a warning because of the wrong index type.

You have to convert/cast to a String first:
echo $array[(string)$val];

This will work as expected, because converting will call the __toString() method. Therefor echo works too:
echo $val; // will display the name
up
2
mail at kleineedv dot de
8 years ago
I had a problem with simplexml reading nodes from an xml file. It always return an SimpleXML-Object but not the text inside the node.

Example:
<?xml version="1.0" encoding="UTF-8"?>
<Test>
    <Id>123</Id>
</Test>

Reading this xml into a variable called $xml and then doing the following
<?php
$myId
= $xml->Id;
?>
Did not return 123 in $myId, but instead I got a SimpleXMLElement Object.

The solution is simple, when you know it. Use explicit string conversion.
<?php
$myId
= (string)$xml->Id;
?>
up
5
xaviered at gmail dot com
5 years ago
Here is a recursive function that will convert a given SimpleXMLElement object into an array, preserving namespaces and attributes.

<?php
function xmlObjToArr($obj) {
       
$namespace = $obj->getDocNamespaces(true);
       
$namespace[NULL] = NULL;
       
       
$children = array();
       
$attributes = array();
       
$name = strtolower((string)$obj->getName());
       
       
$text = trim((string)$obj);
        if(
strlen($text) <= 0 ) {
           
$text = NULL;
        }
       
       
// get info for all namespaces
       
if(is_object($obj)) {
            foreach(
$namespace as $ns=>$nsUrl ) {
               
// atributes
               
$objAttributes = $obj->attributes($ns, true);
                foreach(
$objAttributes as $attributeName => $attributeValue ) {
                   
$attribName = strtolower(trim((string)$attributeName));
                   
$attribVal = trim((string)$attributeValue);
                    if (!empty(
$ns)) {
                       
$attribName = $ns . ':' . $attribName;
                    }
                   
$attributes[$attribName] = $attribVal;
                }
               
               
// children
               
$objChildren = $obj->children($ns, true);
                foreach(
$objChildren as $childName=>$child ) {
                   
$childName = strtolower((string)$childName);
                    if( !empty(
$ns) ) {
                       
$childName = $ns.':'.$childName;
                    }
                   
$children[$childName][] = xmlObjToArr($child);
                }
            }
        }
       
        return array(
           
'name'=>$name,
           
'text'=>$text,
           
'attributes'=>$attributes,
           
'children'=>$children
       
);
    }
?>
up
2
charlie at blankcanvasstudios dot com
9 years ago
Optimizing aalaap at gmail dot com's php

<?php
function is_rss($feedxml) {
    @
$feed = simplexml_load_string($feedxml);

    return (
$feed->channel->item)?true:false;
}

function
is_atom($feedxml) {
    @
$feed = new SimpleXMLElement($feedxml);
    (
$feed->entry):true:false;
}
?>
up
4
philipp at strazny dot com
6 years ago
Here's a quick way to dump the nodeValues from SimpleXML into an array using the path to each nodeValue as key. The paths are compatible with e.g. DOMXPath. I use this when I need to update values externally (i.e. in code that doesn't know about the underlying xml). Then I use DOMXPath to find the node containing the original value and update it.

<?php
function XMLToArrayFlat($xml, &$return, $path='', $root=false)
{
   
$children = array();
    if (
$xml instanceof SimpleXMLElement) {
       
$children = $xml->children();
        if (
$root){ // we're at root
           
$path .= '/'.$xml->getName();
        }
    }
    if (
count($children) == 0 ){
       
$return[$path] = (string)$xml;
        return;
    }
   
$seen=array();
    foreach (
$children as $child => $value) {
       
$childname = ($child instanceof SimpleXMLElement)?$child->getName():$child;
        if ( !isset(
$seen[$childname])){
           
$seen[$childname]=0;
        }
       
$seen[$childname]++;
       
XMLToArrayFlat($value, $return, $path.'/'.$child.'['.$seen[$childname].']');
    }
}
?>

Use like this:

<?php
$xml
= simplexml_load_string(...some xml string...);
$xmlarray = array(); // this will hold the flattened data
XMLToArrayFlat($xml, $xmlarray, '', true);
?>

You can also pull multiple files in one array:

<?php
foreach($files as $file){
   
$xml = simplexml_load_file($file);
   
XMLToArrayFlat($xml, $xmlarray, $file.':', true);
}
?>
The respective filename/path is thus prefixed to each key.
up
3
streaver91 at gmail dot com
6 years ago
The BIGGEST differece between an XML and a PHP array is that in an XML file, the name of elements can be the same even if they are siblings, eg. "<pa><ch /><ch /><ch /></pa>", while in an PHP array, the key of which must be different.

I think the array structure developed by svdmeer can fit for XML, and fits well.

here is an example array converted from an xml file:
array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@text"=>"some text",
)

or if it has childrens, that can be:

array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@items"=>array(
    0=>array(
        "@tag"=>"name","@text"=>"some text"
    )
)

Also, I wrote a function that can change that array back to XML.

<?php
function array2XML($arr,$root) {
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><{$root}></{$root}>");
$f = create_function('$f,$c,$a','
        foreach($a as $v) {
            if(isset($v["@text"])) {
                $ch = $c->addChild($v["@tag"],$v["@text"]);
            } else {
                $ch = $c->addChild($v["@tag"]);
                if(isset($v["@items"])) {
                    $f($f,$ch,$v["@items"]);
                }
            }
            if(isset($v["@attr"])) {
                foreach($v["@attr"] as $attr => $val) {
                    $ch->addAttribute($attr,$val);
                }
            }
        }'
);
$f($f,$xml,$arr);
return
$xml->asXML();
}
?>
up
1
Serge
2 years ago
XML data values should not contain "&" and that need to be replaced by html-entity "&amp;"

You can use this code to replace lonely "&" to "&amp;":

<?php
$sText
= preg_replace('#&(?![a-z]{1,6};)#i', '&amp;', $sText);
?>

This will replace just "&" into "&amp;" but dont touches other html-entities like "&nbsp;", "&lt;" etc and, of course, "&amp;".

P.S. In regexp max length is 6 becouse I found that is the maximum length of possible html entity using this code:
<?php
max
(array_map('strlen', array_values(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5)))) - 2
?>
minus two is for first "&" and last ";" in an any html entity.
up
4
dkrnl at yandex dot ru
4 years ago
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

Usage example: http://github.com/dkrnl/SimpleXMLReader/blob/master/examples/example1.php

<?php

/**
* Simple XML Reader
*
* @license Public Domain
* @author Dmitry Pyatkov(aka dkrnl) <dkrnl@yandex.ru>
* @url http://github.com/dkrnl/SimpleXMLReader
*/
class SimpleXMLReader extends XMLReader
{

   
/**
     * Callbacks
     *
     * @var array
     */
   
protected $callback = array();

   
/**
     * Add node callback
     *
     * @param  string   $name
     * @param  callback $callback
     * @param  integer  $nodeType
     * @return SimpleXMLReader
     */
   
public function registerCallback($name, $callback, $nodeType = XMLREADER::ELEMENT)
    {
        if (isset(
$this->callback[$nodeType][$name])) {
            throw new
Exception("Already exists callback $name($nodeType).");
        }
        if (!
is_callable($callback)) {
            throw new
Exception("Already exists parser callback $name($nodeType).");
        }
       
$this->callback[$nodeType][$name] = $callback;
        return
$this;
    }

   
/**
     * Remove node callback
     *
     * @param  string  $name
     * @param  integer $nodeType
     * @return SimpleXMLReader
     */
   
public function unRegisterCallback($name, $nodeType = XMLREADER::ELEMENT)
    {
        if (!isset(
$this->callback[$nodeType][$name])) {
            throw new
Exception("Unknow parser callback $name($nodeType).");
        }
        unset(
$this->callback[$nodeType][$name]);
        return
$this;
    }

   
/**
     * Run parser
     *
     * @return void
     */
   
public function parse()
    {
        if (empty(
$this->callback)) {
            throw new
Exception("Empty parser callback.");
        }
       
$continue = true;
        while (
$continue && $this->read()) {
            if (isset(
$this->callback[$this->nodeType][$this->name])) {
               
$continue = call_user_func($this->callback[$this->nodeType][$this->name], $this);
            }
        }
    }

   
/**
     * Run XPath query on current node
     *
     * @param  string $path
     * @param  string $version
     * @param  string $encoding
     * @return array(SimpleXMLElement)
     */
   
public function expandXpath($path, $version = "1.0", $encoding = "UTF-8")
    {
        return
$this->expandSimpleXml($version, $encoding)->xpath($path);
    }

   
/**
     * Expand current node to string
     *
     * @param  string $version
     * @param  string $encoding
     * @return SimpleXMLElement
     */
   
public function expandString($version = "1.0", $encoding = "UTF-8")
    {
        return
$this->expandSimpleXml($version, $encoding)->asXML();
    }

   
/**
     * Expand current node to SimpleXMLElement
     *
     * @param  string $version
     * @param  string $encoding
     * @param  string $className
     * @return SimpleXMLElement
     */
   
public function expandSimpleXml($version = "1.0", $encoding = "UTF-8", $className = null)
    {
       
$element = $this->expand();
       
$document = new DomDocument($version, $encoding);
       
$node = $document->importNode($element, true);
       
$document->appendChild($node);
        return
simplexml_import_dom($node, $className);
    }

   
/**
     * Expand current node to DomDocument
     *
     * @param  string $version
     * @param  string $encoding
     * @return DomDocument
     */
   
public function expandDomDocument($version = "1.0", $encoding = "UTF-8")
    {
       
$element = $this->expand();
       
$document = new DomDocument($version, $encoding);
       
$node = $document->importNode($element, true);
       
$document->appendChild($node);
        return
$document;
    }

}
?>
up
3
maikel at yuluma dot com
4 years ago
In reply to  soloman at textgrid dot com,

2 line XML2Array:

$xml = simplexml_load_string($file);
$array = (array)$xml;
up
1
oscargodson at gmail dot com
8 years ago
To add to what others have said, you can't directly put a $_GET or $_POST value into a variable then into an attribute using SimpleXML. You must first convert it to an integer.

This will NOT work

<?php
      $page_id
= $_GET['id'];
      echo
$xml->page[$page_id]
?>

You will get something like:
Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/mysite/index.php on line 10

However, this WILL work and is much simpler then using (string) or other methods.
<?php
   $page_id
= intval($_GET['id']);
   echo
$xml->page[$page_id]
?>
up
2
aalaap at gmail dot com
9 years ago
Here are two quick and dirty functions that use SimpleXML to detect if a feed xml is RSS or ATOM:

<?php
function is_rss($feedxml) {
    @
$feed = new SimpleXMLElement($feedxml);

    if (
$feed->channel->item) {
        return
true;
    } else {
        return
false;
    }
}

function
is_atom($feedxml) {
    @
$feed = new SimpleXMLElement($feedxml);

    if (
$feed->entry) {
        return
true;
    } else {
        return
false;
    }
}
?>

The functions take in the full text feed (retrieved via cURL, for example) and return a true or a false based on the result.
up
1
sherwinterunez at yahoo dot com
7 years ago
<?php

// Sherwin R. Terunez
//
// This is my own version of XML Object to Array
//

function amstore_xmlobj2array($obj, $level=0) {
   
   
$items = array();
   
    if(!
is_object($obj)) return $items;
       
   
$child = (array)$obj;
   
    if(
sizeof($child)>1) {
        foreach(
$child as $aa=>$bb) {
            if(
is_array($bb)) {
                foreach(
$bb as $ee=>$ff) {
                    if(!
is_object($ff)) {
                       
$items[$aa][$ee] = $ff;
                    } else
                    if(
get_class($ff)=='SimpleXMLElement') {
                       
$items[$aa][$ee] = amstore_xmlobj2array($ff,$level+1);
                    }
                }
            } else
            if(!
is_object($bb)) {
               
$items[$aa] = $bb;
            } else
            if(
get_class($bb)=='SimpleXMLElement') {
               
$items[$aa] = amstore_xmlobj2array($bb,$level+1);
            }
        }
    } else
    if(
sizeof($child)>0) {
        foreach(
$child as $aa=>$bb) {
            if(!
is_array($bb)&&!is_object($bb)) {
               
$items[$aa] = $bb;
            } else
            if(
is_object($bb)) {
               
$items[$aa] = amstore_xmlobj2array($bb,$level+1);
            } else {
                foreach(
$bb as $cc=>$dd) {
                    if(!
is_object($dd)) {
                       
$items[$obj->getName()][$cc] = $dd;
                    } else
                    if(
get_class($dd)=='SimpleXMLElement') {
                       
$items[$obj->getName()][$cc] = amstore_xmlobj2array($dd,$level+1);
                    }
                }
            }
        }
    }

    return
$items;
}

?>
up
0
oleg at mastak dot fi
1 year ago
Two lines xml2array:

<?php

$xml
= simplexml_load_string($xmlstring);
$array = (array) $xml;

?>
up
-2
charles dot a dot dacosta at gmail dot com
11 months ago
I had to do the following to catch the fact that my simplexml_load_string call was not working right (it was returning empty objects).

$statistik = simplexml_load_string($record,"SimpleXMLElement",LIBXML_NSCLEAN,$ns,TRUE);

    if (($statistik === FALSE) or ($statistik === NULL) or empty($statistik))
    {
        echo "$ctr) STATISTIK ERROR---\n";
        var_dump($statistik);
        echo "\n\n";
        echo "Failed loading XML\n";
        foreach(libxml_get_errors() as $error)
        {
            echo "\n", $error->message;
        }
        die();
    }

before I put the check for "empty()" I was not catching the error.
up
0
whyme
4 years ago
Simple means simple.  If you know the structure and just want the value of a tag:

<?php
$xml
= simplexml_load_file($xmlfile);
print
$xml->City->Street->Address->HouseColor;
?>

Warning, numbers can come out as strings, empty elements like <HouseColor></HouseColor> come out as array(0)
up
0
Laurent Vervisch
5 years ago
Here is an example of an easy mapping between xml and classes defined by user.

<?php
class XmlClass extends SimpleXMLElement
{
   
/**
     * Returns this object as an instance of the given class.
     */
   
public function asInstanceOf($class_name)
    {
       
// should check that class_name is valid

       
return simplexml_import_dom(dom_import_simplexml($this), $class_name);
    }

    public function
__call($name, array $arguments)
    {
        echo
"magic __call called for method $name on instance of ".get_class()."\n";

       
// class could be mapped according $this->getName()
       
$class_name = 'Test';

       
$instance = $this->asInstanceOf($class_name);
        return
call_user_func_array(array($instance, $name), $arguments);
    }
}

class
Test extends XmlClass
{
    public function
setValue($string)
    {
       
$this->{0} = $string;
    }
}

$xml = new XmlClass('<example><test/></example>');
$test = $xml->test->asInstanceOf('Test');
echo
get_class($xml->test), "\n";
echo
get_class($test), "\n";

$test->setValue('value set directly by instance of Test');
echo (string)
$xml->test, "\n";
echo (string)
$test, "\n";

$xml->test->setValue('value set by instance of XmlClass and magic __call');
echo (string)
$xml->test, "\n";
echo (string)
$test, "\n";
?>

XmlClass
Test
value set directly by instance of Test
value set directly by instance of Test
magic __call called for method setValue on instance of XmlClass
value set by instance of XmlClass and magic __call
value set by instance of XmlClass and magic __call
up
0
thedoc8786 at gmail dot com
5 years ago
I know it is over-done, but the following is a super-short example of a XML to Array conversion function (recursive):

<?php
   
function toArray(SimpleXMLElement $xml) {
       
$array = (array)$xml;

        foreach (
array_slice($array, 0) as $key => $value ) {
            if (
$value instanceof SimpleXMLElement ) {
               
$array[$key] = empty($value) ? NULL : toArray($value);
            }
        }
        return
$array;
    }
up
0
phil at dier dot us
6 years ago
Here's a function I came up with to convert an associative array to XML.  Works for multidimensional arrays as well.

<?php
function assocArrayToXML($root_element_name,$ar)
{
   
$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
   
$lass="default">SimpleXkeyword">= c
//
$$v  return (<($v&  return teaddCd">a($kspan class="default">$lan class="defa( $lan class="defa( teaddCd">a($k,$v&pan class="default">$lan class="defa( $lan class="defa( echo (string)$lass="default">SimpleXkeyword">=/span>$root_element_name$level)
{
    $lult">$array
test$r/nan clasault">?>

The functi
0981v id="Vu101949"> up
0981v0
phil at dier dot us
7 years agago<8 05:14/div>
I know it is over-done, but the st wanand the fyworbsp;n (r">); array iv>short examCDATA e="ts="dre <?php= ,"SimpleXMLElemen">);(   &n">);em>p, class="keyword">) , >
&OCDATA)p;   forbject XML.&nsmCDATA e fSt (it iiv> $staven cl
410iv id="Vu108035"> up
410ivnotes-voco0v>
410ivnuser">phil at dier dot us
9 years 9- aga6 07:22/div>
I know it is over-done, but theife of yinglulasonsx wannampl value $stard">indefaeorb  sl is RSS br /> ard">inaL to e $stault"><?php exe is : ult"><?php
$xml c ($xmlfile)claapiic< /> ()claapiic)claapid">($t">testlist_)claapidd">= 'Te /> (iicar)claapi/span>$t">testaret;?xml version=\"1.0\"?><t">$key $xml test$lass="default">SimpleXkeyword">list_)claapidd">=/span>$key$++">$ddputait;?xml version=\"1.0\"?><nan clasault">?>

The functions take in the full
6263v id="Vu108035"> up
6263v0
6263v0user">phil at dier dot us
7 years ago2-17rong21/div>
I know it is over-done, but thedyem>ic sql iivl"> us$sta!" ault"><?php ">, .!" ault">&l
$xml ;
    }
}   r />The functions take in thn clsqlnctions taks="defa(
)nctions taks="defa(
$lan class="defa( cl on inriteria="byId"nctiWHEREpco>$d%dd">{< on nctions taks="defa(
{< on nctiions taks="defa(
)nctions taks cl/sqlnctions takons takindexplexault">&l
$xml function assocArrayToXML$xmlfiled  return 'Te />&nb
m>p'> $value echo (string)$lan class="default">$lt">$issetstring
$keydkeysimplexml_import_dom$=/span>$root_element_namedkey$keydkey$lban class="default">$lan class="default">$lult">$array?&(">= simplexml_load_file($xmlfile, .!" ;
   
$xml->test)gt;test$r/nan clasml $xml()
    {
&nbsnan clasml
simplexml_load_file($xmlstring)
    {
&nbsnan clast">get_class
5762v id="Vu108035"> up
5762v0
5762v0user">phil at dier dot us
7 years ago1-20 12:>
I know it is over-done, but thewh>); us$staote upr.
$xrd">infromr.as (+ * - / ) yingl; &nbs hme()as oiv> operat">a,ghe giML becaed xofaote upr.$xm= 'Test'simplexml_load_file    } = simplexml_load_fileTestan cld">=cbr yings="keys cl/d">=cbr />Testan cl iz cbr 11.45s cl/siz cbr ns taks cl/!" cbr

        =gsimplexml_load_file($xmlstringget_classtest$ltts fanbsp; &nbing(d>-&t">te iz g betwven cla(">$)11r />ult">$l(45) n;   function get_classge(fywotxml      &n;urn The functi
87083v id="Vu108035"> up
phil at dier dot us
9 years 8gago<8 02:27/div>
Simple means simple.  If yoto $st lass="keyword">) rd">is iiv$_SESSION>doeurning emp. Savdiv> <
sass. iiv> dreornce"s strin: sesan cdrdart() [fault">a.sesan c-rdart]: Nit n fywnglasexists"
  <?php<"defaul"defaul$!" cdefaullt">Silass="keyword">)($" tibsp;     }-&t">teResp>aset">tePlacemarkt">teord">-&Det clsp; &nCountryp; &nCountry; &nCit sp;     }$d$countryp;   forbjectwill< emplt"><?php<"defaul"defaul$_SESSION['country'">$dault">$td$countryp;
85674v id="Vu108035"> up
phil at dier dot us carveryahooass="genanchor" href="#120167"> ¶
9 years 8g 9- 1 01:02/div>
Simple means simple.  If yMovdiv>yingl meanfromra PHP 5.2.6 / Win ow tenvi idd">) e fa 5.2.0 / Linuxtenvi idd">), I>yinghowfywstbr />-& e fa plaiiv>="p nit arraiivailass="key br />-&_nit ,vai[0]t;</Hpan> shss= asl value $sta'12'nal arraHowever,nd>-&_nit [0]tan> erd">at$stad">: iiv5.2.0nal arraYwanelemsee belthe val meanchangl I>mat ,vpull$stamy ful e fyingone.;   yingl-&_nit [0];p; -&_nit t">teas>(<());p; $stabrasp;  !" ap;
9735iv id="Vu108035"> up
735ivnotes-vo44iv>
735ivnuser">phil at dier dot usespuss="sh;/Helass="genanchor" href="#120167"> ¶
7 years ago4o
Here is an example of an easy mapping bellass="key e="faulal arraClembe em>the fyworb">($o>lass="keyCop; clembe em>the fperform> <<?php
class ) ">$o>a lass="keyword">) br />&anurns t *;be pro/>-&ass="d val all$staapplicat">alal arrabjectr />ptlass=lt;HouseCurns t *;">(&an"sts fperform> <() back ">$o>a t;Hous,;">(/**
     * Returns this object as an instaWh>); e="fous,;e="fal valuuppliasskey docrd">)r />   
a lass="keyword">) ven claba&asson>yu />-& &ne="fousurns this object as an insta valkey docrd">) ">(   
) locat">ane=thurns this object as an insta@ult">$aven clurns this object as an instan class="keyword">public function
setValue$xmlfiled&nbp; return $mlfile(<_exists/span>$xmlfiled          simplexml_import_dom($xmlfiled&sp; }
      &nbssp; &nbp;        
SimpleXMLElementpt">setValue$xmlfile); "dd$r />    public function    r />The fwdoc/span>d&sp; }
      &nbsn class="default">$lbn class="comment">/**
     * Returns this object as an instaWh>); e="fous,;e="fal valuuppliasskey e $sta />   
a lass="keyword">) ven claba&asson>yu />-& &ne="fousurns this object as an insta valkey e $sta />   
) rd">($aven clurns this object as an instan class="keyword">public function
setValue($xmlstring)
    {
&nbsnbp; return
$issetstring)
    {
&nbsnbsp;        
simplexml_import_dom($xmlstring)
    {
&nbsnp; }
      &nbssp; &nbp;        
SimpleXMLElementpt">setValue$xmlfile$r />    public function    r />The fwrd">)
    {\"?>&\l
d&sp; }
      &nbsn class="default">$lbn class="comment">/**
     * Returns this object as an instaWh>); e="fous,;e="fal valuuppliasskey DOM nit a />   
a lass="keyword">) ven claba&asson>yu />-& &ne="fousurns this object as an insta valkey DOM nit a />   
$aven clurns this object as an instan class="keyword">public function
setValue$xmlfiled&nbp; return $issetstringd          simplexml_import_dom(dom_import_simplexmld&np; }
      &nbssp; &nbp;        
SimpleXMLElementpt">setValue$xmlfile$r />    public function    r />The fwdod&sp; }
      &nbsn class="default">$lbn class="comment">/**
     * Returns this object as an instaWh>); e="fous,;e="fal vallass="keyword">)a />   
a n (r">);, t;Hous,;p; DOM ven claba&asson>yu />-& &urns this object as an instae="fousa valkey DOM nit a />   
) locat">ane=thurns this object as an insta@e="2 atypev(t;Hous,;">({$amixedurns this object as an instan class="keyword">public function
setValue$root_element_name($/value $/value $issetstring($) classclass issetstring$          artype/span>$&nbp;        
    &nbs: />    $array
($t">test$r/n />        (<

    &nbs: />    $issetstring
$asp; $array($t">test$rtringSimpleXMLElementpt">setValue$xmlfile($r />    public function    r />The fwe=thur />    {\"?>&\l
d&sp; }
               
    &nbs: />    $array
($string($)n />              &nbssp; &nbp;         SimpleXMLElementpt">setValue$xmlfile$r />    public function    r />The fwrword">(d&sp; }
      &nbsn class="default">$lbn clas}n clasml
The functi
0
0 class="m>thedoc8786 at gmail dot com
6 years ago
Here's a function I came up witFAIL!abjectfault">sews as better br iv> onl I>postass=elthlt"><?php
   
function toArray(SimpleXMLElement $xml) {
        $array = (array)    } $xmlfiled&sp; }
      &nbp; }
      &nbefault">array_slice
($array, 0) as $key => $value
) {
            if (
$vlt">$value) ? )array =? ] = empty(:= empty($value ($array) ? )array =? ] = empty(($value);
            }
  &nb}t"><?php$array
;
    }
5697v id="Vu101949"> up
5697vnotes-vo37iv>
5697vn class="m>thedoc8786 at gmail dot comyeywstudioass="genanchor" href="#120167"> ¶
6 years ago9-07 06:25/div>
Here's a function I came up witNonl  XML2d">(ss br />Ibefund satisfiassngl me uptelyrabjeir<
sadidrningalw clafiivbsp;pron claItan> ws aousadn,l />walidasons taks clfialdsyword">{fiald/yword">{fiald/yword">{fiald/yword">{/fialdsywor/span>&l
$xml function $o>ane />&n. P wanspaine.n clbr/nctions tak *;Fp; &sion f,g of a given ;</Hons tak *;( cl a fnctions tak *;d">{fiald "m>t="ying; &n"atype="yingType"/nctions tak *;d">{/ a fnctions tak *;d">{brnctions tak *;ist wan>;<['fiald']['>m>p'efau'ying; &n'ions tak *;rd">;<['fiald']['type'efau'yingType'ions tak *;d">{/ a fnctions tak *;Ist wan>;<['fiald']['@/atribu ']['>m>p'efau'ying; &n'ions tak *;d">{/ a fnctions tak *;d">{brncti__________________________________________________________d">{brnctions tak *;Repeat$stafialdse /e stfaud iivindexud pan cl.fyig of a markup sut">as:ons tak *;( cl a fnctions tak *;( cle="">)nctions tak *sp; pu( cl d">a">tead">{/ d">a">teons tak *sp; pu( cl d">a">tebd">{/ d">a">teons tak *sp; pu( cl d">a">tecd">{/ d">a">teons tak * > ons tak *;d">{/ a fnctions tak *; wanrd">= walid;<['e="">)'][' d">a'][0efau'a'ions tak *;rd">;<['e="">)'][' d">a'][1efau'b'eons tak * > And soadn ons tak *;d">{/ a fnctions tak *;@e="2)
$!" cdefaulsp;    
$/atribu Keys/code>
ist wanpspa TRUE,"sta rd">is will wan&an"sts fpspa a t;Housons tak *sp; dpan>
$rd">aretKeys/code>
ist wanpspa TRUE,"sta rd">is willaret'vindex.ons tak *sp; wan&an"sts fpspa a t;Housons tak *sp; dpan>
$rd">iKeys/code>
s/code>
ist wanpspa TRUE,"sta rd">is willis'vindex.bNoteons tak *sp; wan&an"sts fpspa a t;Hous e ons tak *sp; dpan>$ard">= <
$staa/>&n.ons tak */ord">function assocArrayToXML($value) w>) {
      &,rray
aretKeygt;       &,rrayiKeygt;       &)bsp; retan class="default">$lt"valuearetKey {
      &classclass !alue
($xmlstringaretKeygt; aretKey {
      &simplexml_load_filearet'br />    } $lt"value($xmlstring$lt"valueiKey {
      &classclass !alue
($xmlstringiKeygt; iKey {
      &simplexml_load_fileis'br />    }
$array (= 'Test'test=/span>$bsp() {
      &auey
doault">$tmlfile)gt; ) {
      &auey
$lt"value)gt;       &)bsp; rets/code>
s/code>
isxmlstringiKeygt; $? iKeygt; $dd_rd">)gt; $lult">$lult">$lp; &{alue$ 'Test')gt; $lban classp; return aretarray (simplexml_load_filetestaret/span>$bs">$key = 'Tt">$value a{
      &)bsp; rets/code>
s/code>
alue ) {
      &simplexml_load_file
($valuea{
      &,rray
aretKeygt; iKeygt; aret/span>$key=gt;
s/code>
s/code>
isxmlstring($arrayaret/span>$key=gt;
s/code>
s/code>
s/code>
isxmlstring'Test'aret/span>$key=gt; unsetstringaret/span>$key=gt; tringaret/span>$key=gt; $ddtesprt;       &frray ban class="default">$lult">$lult">$l tringaret/span>$key=gt; $ddrd">)gt; $lult">$lult">$l }p; &{an class="default">$lult">$lult">$l tringaret/span>$key=gt; &nbtringaret/span>$key=gt; igt; $lult">$lult">$lban class="default">$lult">$lult">$lp; &{( tringaret/span>$key=gt; $ddrd">)gt; $lult">$lult">$lban class="default">$lban class/code> isxmlstringaret/span>$)bsp; rets/code> s/code> isxmlstringaretKeygt; $? aretKeygt; $ddrd">aret/span>$/ban class="default">$lult">$lult">$lp; &{alue$ 'Test'$array$? aretgt; $lban classp; return test$bs">$key =gt; testigt; $key=gt; dorrayigt; $lt"value$)bsp; rets/code> s/code> isxmlstring$? $dddatribu /span>$/ban class="default">$lult">$lult">$lp; &{alue$ 'Test'$array$? datribu /span>$spban class="default">$lban classp; return $array$?
14201v id="Vu101949"> up
6 year8iv>
6 years 4-01/stro8:22/div>
Here's a function I came up witkey tod">( neap; = = (rd">=) n class="kywordrd">(<(d>-&bsp; &nbp; &nbEnjoy!
91494v id="Vu108035"> up
1494vng>6 year8iv>
1494vn class="m>thedoc8786 at gmail dot com ¶
9 years 9-06-12ro7:58/div>
Here's a function I came up witWs aousafixg of lass="key + memclt"e bug.an classp; retImprovcla meanat> http://tinyurl.>asnof meaniivspregbr />&alid-- butgiiv emps!an classp; retpan>fu**
     * #o XML.&n a t;Hucturegbr />m(fu*#i />&n-ba&asst;Huctureg(br />&anfu*#al arra> tiiclueasluupportl of rte up!" !ord">fu*#i(nb:>m(fu**
   ="defaultfault">assocArrayToXML
($array$s bsp; rets/code>ddd">= (array)=)rray$p($value($)s bsp; rets/codes/code>ddd">= (array)efault"xmlfile= (array)=gt; testigt; dorrayigt; dorrayigt; )'br />    } urn mlstring'Test'($array) ? $lult">$lisx!alue ($arrayurn
mlstring'Test'    } <.drd">)gt; $lult">$lban class="default">$lult">$lalue($key] = empty($ult">$lban class="default">$s="defap;   rets/codeault">$lult">$lalue($key] = empty(($array) ? $ult">$lban class="default">$lban class/code>
p;   rets/codeault">$ult">$lalue($key] = empty(rd">)gt; $l}sp; rets/codes/code>}($array;
    }
fu*ban clasrray
addfa > 08-06e" id= a>#10194/elt">a>