SimpleXML
在线手册:中文 英文
PHP手册

范例

Table of Contents


SimpleXML
在线手册:中文 英文
PHP手册
PHP手册 - N: 范例

用户评论:

Juan Herrera (19-Dec-2009 08:49)

When using simplexml to access a element the returned object may be a SimpleXMLElement instead of a string.

Example:

<?php
$string
= <<<XML
<?xml version='1.0'?>
<document>
    <cmd>login</cmd>
    <login>Richard</login>
</document>
XML;
                                                                       
                                          
$xml = simplexml_load_string($string);
print_r($xml);
$login = $xml->login;
print_r($login);
$login = (string) $xml->login;
print_r($login);
?>

Expected result:
----------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
Richard
Richard

Actual result:
--------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
SimpleXMLElement Object
(
    [0] => Richard
)
Richard

But this is an intended behavior. See http://bugs.php.net/bug.php?id=29500

info at accountr dot eu (05-May-2009 04:35)

Instead of using  <?php eval($code) ?>

you can use this method,

<?php

$node
= "node";

$XML = simplexml_load_file($file);

$text = (string)$XML->nodes->{$node}; // works
// or
$text2 = (string)$XML->{$node}->child; // also works fine

?>

I think it is much more easier instead of eval().

Edward Rudd (14-Nov-2008 04:46)

If you need to updated the content of a node selected via Xpath use [0].  Example.
<?php
$x
= new SimpleXMLElement(<<<EOXML
<root>
   <node>Some Text</node>
</root>
EOXML
);

$nodes = $x->xpath('/root/node');

// This does not work
// $nodes[0] = "My New Text";
$nodes[0][0] = "My New Text";

echo
$x->asXML();
?>

Note that this for some reason doesn't work.
<?php
$node
= $nodes[0];
$nodes[0] = "My New Text";
?>
It throw an exception "Object ($node) don't support array access operators"

Kari P. (15-Aug-2008 10:17)

To take care of proper error checking, one must use try-catch blocks:

<?php
try {
 
$sxe = new SimpleXMLElement($xmlstring);
} catch (
Exception $e) {
  echo
"bad xml";
}
?>

To get rid of warnings, use @ in front of new:

<?php
try {
 
$sxe = @new SimpleXMLElement($xmlstring);
} catch (
Exception $e) {
  echo
"bad xml";
}
?>

dipl dot paed dot thomas dot schaefer at web dot de (03-May-2008 05:57)

<?php
class QXML {
  ...
  protected function
_toXML(
   
$xmlArray,
   
$elmName='graph',
   
$elmCloseTag="",
   
$level=0)
  {
   
$xmlString = "";
    if(
is_array($xmlArray)){
     
$strXmlAttributes = "";
     
$key_xml = "";
     
$keysXmlArray = array_keys($xmlArray);
     
$curLevel = $level + 1;
      if(
in_array(self::attribute,$keysXmlArray)){
        if(isset(
$xmlArray[self::attribute])){
          if(
is_array($xmlArray[self::attribute])){
            foreach(
$xmlArray[self::attribute]
              as
$xmlArrayKey => $xmlArrayValue)
            {
             
$strXmlAttributes .= sprintf(' %s="%s"',
                                   
$xmlArrayKey,
                                   
addslashes($xmlArrayValue));
            }
          }
        }
        unset(
$xmlArray[self::attribute]);
      }
      if(
in_array(self::textNode,$keysXmlArray)){
        if(isset(
$xmlArray[self::textNode])){
          if(
$xmlArray[self::textNode]){
           
$key_xml = $xmlArray[self::textNode];
          }
          if(
strlen($ky_xml)){
           
$key_xml = sprintf("<![CDATA[%s]]>",$key_xml);
          } else {
           
$key_xml = "";
          }
        }
        unset(
$xmlArray[self::textNode]);
      }
     
$keysXmlArray=array_keys($xmlArray);
      if(
$elmCloseTag){
       
$indent=str_repeat(" ",$level * 5);
       
$xmlString  .="\n".$indent.
                   
"<".$elmCloseTag.$strXmlAttributes.">".
                   
$key_xml;
      }
      if(
is_array($xmlArray) && count($xmlArray)>0
       
&& count($keysXmlArray)>0)
      {
       
reset($xmlArray);
        foreach(
$keysXmlArray as $key){
         
$altKey = $altKeyXml = $xmlArray[$key];
         
$check = false;
          foreach(
array_keys($altKeyXml) as $j=>$p){
            if(
is_numeric($j)){
             
$check=true;
             
$xmlString.= $this->_toXML(
               
$altKeyXml[$j],
               
"",
               
$key,
               
$curLevel
             
);
              unset(
$altKeyXml[$j]);
            }
          }
          if(
$check){
           
$altKey = $altKeyXml;
          }
          if(
$altKey){
           
$xmlString .= $this->_toXML($altKey,"",$key,$curLevel);
          }
        }
      }
      if(
$elmCloseTag){
       
$xmlString.= (count($xmlArray)>0?"\n".$indent:"").
                    
"</".$elmCloseTag.">";
      }
    }

    if(
$elmName) {
     
$xmlString = "<?xml version='1.0' encoding='UTF-8'?>\n$xmlString\n";
    }
    return
$xmlString;
  }

...
}
?>

Honeymonster (30-Apr-2008 02:52)

@david b
@Fabi W

Why can't you use the ->{} operators?

e.g

$xml->{$node}

I've not tested this, but see no reason why it would not work.

Fabi W (23-Apr-2008 08:34)

@david b's approach of dynamically accessing xml-elements:

You can explode the dynamic var with '->' as seperator and thus build a simple function to get the element

function simplexml_get_node_by_query($sxml_obj, $query)
{
      $nodes = explode("->", $query);
      $currTree = $sxml_obj;

      foreach($nodes as $node)
      {
        $currTree = $currTree->$node;
      }
      return $currTree;
}

mike at mike-griffiths dot co dot uk (18-Apr-2008 05:11)

It is important that you select the correct method of loading the XML in depending on the format of your XML file.

If you use the wrong function to load it in you will get some strange errors.

david b (12-Apr-2008 11:04)

Use eval() when using variable variables to access SimpleXML nodes.
e.g.

<?php
include 'example.php';

$xml = new SimpleXMLElement($xmlstr);

$s = 'movie[0]->plot' ;

echo
"\n1: OK   " . $xml->movie[0]->plot ;   // OK
echo "\n2: FAIL " . $xml->$s ;               // FAIL
echo "\n3: OK   " . eval( "return  \$xml->$s ;" ) ;    // OK

?>