Наша группа в телеграмм для обмена идеями, проектами, мыслями, людьми в сфере ИТ г.Ростова-на-Дону: @it_rostov

SimpleXML


User Contributed Notes 28 notes



28
soloman at textgrid dot com2 years ago
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);


3
Laurent Vervisch1 year ago
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";


3
thedoc8786 at gmail dot com1 year ago
    function toArray($xml) {
        $array = json_decode(json_encode($xml), TRUE);
        
        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( empty($value) ) $array[$key] = NULL;
            elseif ( is_array($value) ) $array[$key] = toArray($value);
        }
        return $array;
    } 
 
3 
 aalaap at gmail dot com ¶5 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;
    }
}


4
sherwinterunez at yahoo dot com3 years ago
// 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;
}


1
maikel at yuluma dot com1 month ago
function array2XML($arr,$root) {
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"


1
mahmutta at gmail dot com3 years ago
$name = "somestring";
$size = 11.45;
$xml = '
<xml>
 <name>somestring</name>
 <size>11.45</size>
</xml>';
 
$xmlget = simplexml_load_string($xml)
echo $xml->size*2;    // 20  its false
// ($xml->size is an object (int)11 and  (45) )
// this is true
echo $size*2;            // 22.90 
echo (float)$size*2;   // 22.90


1
phil at dier dot us2 years ago
function assocArrayToXML($root_element_name,$ar)
{
    $xml = new SimpleXMLElement("<?xml version=\"1.0\"


1
thedoc8786 at gmail dot com1 year ago
    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;
    } 
 
0 
 dkrnl at yandex dot ru ¶2 months 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;
    }
}


0
Anonymous5 months ago
$xml = simplexml_load_file($xmlfile);
print $xml->City->Street->Address->HouseColor;


0
xaviered at gmail dot com1 year ago
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
        );
    }


0
xananax at yelostudio dot com2 years ago
/**
 * Converts a simpleXML element into an array. Preserves attributes.<br/>
 * You can choose to get your elements either flattened, or stored in a custom
 * index that you define.<br/>
 * For example, for a given element
 * 
[php]

 * 
 *
 *
 * if you choose to flatten attributes, you would get:  *
 * $array['field']['name'] = 'someName';
 * $array['field']['type'] = 'someType';
 *
 * If you choose not to flatten, you get:  *
 * $array['field']['@attributes']['name'] = 'someName';
 *
 *
__________________________________________________________
 * Repeating fields are stored in indexed arrays. so for a markup such as:  *
 * 
 *     a
 *     b
 *     c
 * ...
 *
 * you array would be:  *
 * $array['parent']['child'][0] = 'a';
 * $array['parent']['child'][1] = 'b';
 * ...And so on.
 *
 * @param simpleXMLElement    $xml            the XML to convert  * @param boolean|string    $attributesKey    if you pass TRUE, all values will be  *                                            stored under an '@attributes' index.  *                                            Note that you can also pass a string  *                                            to change the default index.
 *                                            defaults to null.  * @param boolean|string    $childrenKey    if you pass TRUE, all values will be  *                                            stored under an '@children' index.  *                                            Note that you can also pass a string  *                                            to change the default index.
 *                                            defaults to null.  * @param boolean|string    $valueKey        if you pass TRUE, all values will be  *                                            stored under an '@values' index. Note  *                                            that you can also pass a string to  *                                            change the default index.
 *                                            defaults to null.  * @return array the resulting array.  */ function simpleXMLToArray(SimpleXMLElement $xml,$attributesKey=null,$childrenKey=null,$valueKey=null){     if($childrenKey && !is_string($childrenKey)){$childrenKey = '@children';}     if($attributesKey && !is_string($attributesKey)){$attributesKey = '@attributes';}     if($valueKey && !is_string($valueKey)){$valueKey = '@values';}     $return = array();     $name = $xml->getName();     $_value = trim((string)$xml);     if(!strlen($_value)){$_value = null;};     if($_value!==null){         if($valueKey){$return[$valueKey] = $_value;}         else{$return = $_value;}     }     $children = array();     $first = true;     foreach($xml->children() as $elementName => $child){         $value = simpleXMLToArray($child,$attributesKey, $childrenKey,$valueKey);         if(isset($children[$elementName])){             if(is_array($children[$elementName])){                 if($first){                     $temp = $children[$elementName];                     unset($children[$elementName]);                     $children[$elementName][] = $temp;                     $first=false;                 }                 $children[$elementName][] = $value;             }else{                 $children[$elementName] = array($children[$elementName],$value);             }         }         else{             $children[$elementName] = $value;         }     }     if($children){         if($childrenKey){$return[$childrenKey] = $children;}         else{$return = array_merge($return,$children);}     }     $attributes = array();     foreach($xml->attributes() as $name=>$value){         $attributes[$name] = trim($value);     }     if($attributes){         if($attributesKey){$return[$attributesKey] = $attributes;}         else{$return = array_merge($return, $attributes);}     }     return $return; } [/php]

0
philipp at strazny dot com3 years ago
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].']');
    }
}


0
kristof at viewranger dot com3 years ago
/**
 * XMLParser Class File
 *
 * This class loads an XML document into a SimpleXMLElement that can
 * be processed by the calling application.  This accepts xml strings,
 * files, and DOM objects.  It can also perform the reverse, converting
 * an SimpleXMLElement back into a string, file, or DOM object.
 */
class XMLParser {
    /**
     * While parsing, parse the supplied XML document.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML document file.
     *
     * @param string $doc the xml document location path
     * @return object
     */
    public static function loadFile($doc) {
        if (file_exists($doc)) {
            return simplexml_load_file($doc);
        } else {
            throw new Exception ("Unable to load the xml file " .
                                 "using: \"$doc\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML string.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML string.
     *
     * @param string $string the xml document string
     * @return object
     */
    public static function loadString($string) {
        if (isset($string)) {
            return simplexml_load_string($string);
        } else {
            throw new Exception ("Unable to load the xml string " .
                                 "using: \"$string\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML DOM node.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML DOM node.
     *
     * @param object $dom the xml DOM node
     * @return object
     */
    public static function loadDOM($dom) {
        if (isset($dom)) {
            return simplexml_import_dom($dom);
        } else {
            throw new Exception ("Unable to load the xml DOM node " .
                                 "using: \"$dom\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the SimpleXMLElement.
     *
     * Sets up a XML file, string, or DOM object based on success of
     * parsing the XML DOM node.
     *
     * @param object $path the xml document location path
     * @param string $type the return type (string, file, dom)
     * @param object $simplexml the simple xml element
     * @return mixed
     */
    public static function loadSXML($simplexml, $type, $path) {
        if (isset($simplexml) && isset($type)) {
        switch ($type) {
            case 'string':
                return $simplexml->asXML();
            break;
            case 'file':
                if (isset($path)) {
                    return $simplexml->asXML($path);
                } else {
                    throw new Exception ("Unable to create the XML file. Path is missing or" .
                                         "is invalid: \"$path\"", E_USER_ERROR);
                }
            break;
            case 'dom':
                return dom_import_simplexml($simplexml);
            break;
        }
        } else {
            throw new Exception ("Unable to load the simple XML element " .
                                 "using: \"$simplexml\"", E_USER_ERROR);
        }
    }
}


0
emmanuel3 years ago
function callMe($param) {
    $search = array('byUsername' => 'dynsql');
    
    if (isset($search[$param[1]])) {
        return sprintf($param[2], $search[$param[1]]);
    }
    
    return "";
}
$xml = simplexml_load_file("test.xml");
$string = $xml->statement->asXML();
$string = preg_replace_callback('/<call criteria="(\w+)">(.*?)<\/call>/', 'callMe', $string);
$node = simplexml_load_string($string);
echo $node;


0
antoine dot rabanes at gmail dot com4 years ago
$all_api_call = simplexml_load_file($url);
$all_api = array();
$all_api = $all_api_call->result;
$list_all_api_name = array();
$i = 0;
foreach ($all_api->children() as $funcky_function)
{
    $string_tmp = (string )$funcky_function->function;
    $list_all_api_name[$i++] = $putain;
}


0
walter4 years ago
 # convert a structure that may include objects to a pure
 # array-based structure (that can be stored in memcache)
 #  ... includes support for simplexml!
 # (nb: may have problems with infinite recursive structs)
 function enforce_array($obj) {
  $array = (array)$obj;
  if(empty($array)) {
   $array = '';
  }
  else {
   foreach($array as $key=>$value) {
    if(!is_scalar($value)) {
     if(is_a($value,'SimpleXMLElement')) {
      $tmp = memcache_objects_to_array($value);
      if(!is_array($tmp)) {
       $tmp = ''.$value;
      }
      $array[$key] = $tmp;
     }
     else {
      $array[$key] = enforce_array($value);
     }
    }
    else {
     $array[$key] = $value;
    }
   }
  }
  return $array;
 }


0
mail at kleineedv dot de4 years ago
$myId = $xml->Id;


0
oscargodson at gmail dot com4 years ago
      $page_id = $_GET['id'];
      echo $xml->page[$page_id]


0
bxt at die-optimisten dot net5 years ago
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;
}


-1
Danny from holland4 years ago
print "<pre>";
$root = simplexml_load_string($XML_URL);
$data = get_object_vars($root);
$producten = array();
foreach ($data['product'] as $keys => $values) {
    $producten['product'][$keys] = get_object_vars($data['product']);
    
    foreach ($values as $key => $value) {
        $value = str_replace("\r\n", '<br />', $value);
        $value = str_replace("\r", '<br />', $value);
        $value = str_replace("\n", '<br />', $value);
        $producten['product'][$keys][$key] = $value;
    }
    
}
print_R($producten);
print "</pre>";




Смотрите также:
Описание на ru2.php.net
Описание на php.ru

.

Популярное:


Содержание: