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

search for in the

SimpleXMLElement::attributes> <SimpleXMLElement::addChild
Last updated: Fri, 13 Nov 2009

view this page in

SimpleXMLElement::asXML

(PHP 5 >= 5.0.1)

SimpleXMLElement::asXML SimpleXML 要素に基づき整形式の XML 文字列を返す

説明

mixed asXML ([ string $filename ] )

asXML メソッドは、親オブジェクトのデータを XML version 1.0 形式にフォーマットします。

パラメータ

filename

指定した場合、データを返すかわりにファイルにデータを書き込みます。

返り値

filename が指定されていない場合、この関数は 成功時に string 、エラー時に FALSE を返します。 パラメータが指定されていた場合は、ファイルが正常に書き込めたときに TRUE 、そうでないときに FALSE を返します。

例1 XML を取得する

<?php
$string 
= <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

echo 
$xml->asXML(); // <?xml ... <a><b><c>text</c><c>stuff</c> ...

?>

asXML は Xpath の結果にも適用できます:

例2 SimpleXMLElement::xpath の結果に asXML() を使用する

<?php
// 上の XML の例から続く

/* <a><b><c>を探す */
$result $xml->xpath('/a/b/c');

while(list( , 
$node) = each($result)) {
    echo 
$node->asXML(); // <c>text</c> と <c>stuff</c>
}
?>



SimpleXMLElement::attributes> <SimpleXMLElement::addChild
Last updated: Fri, 13 Nov 2009
 
add a note add a note User Contributed Notes
SimpleXMLElement::asXML
Anonymous
28-Jun-2009 08:23
Getting the subtree without the start and end tags:

<?php
$string
= <<<XML
<a>
 <b>
  <c>text <b>hello</b><i>hello</i></c>
  <c>stuff</c>
 </b>
 <d>
  <c>hella</c>
 </d>
</a>
XML;
//=================================
function subTree( $s , $tag ){
 if(
substr($s,0,1+strlen($tag))!='<'.$tag) return false;
 
$news='';
 for(
$i=1+strlen($tag);$i<strlen($s);$i++){
  if(
substr($s,$i,1) == '>') break;
 }
 
$news=substr($s,$i+1);
 if(
substr($news,strlen($news)-strlen($tag)-3) !='</'.$tag.'>') return false;
 return(
substr($news,0,strlen($news)-strlen($tag)-3));
}
//=================================

$xml = new SimpleXMLElement($string);

echo
'<textarea rows="10" cols="40">' . $xml->asXML() . '</textarea><br />';
echo
'<textarea rows="6" cols="40">' . $xml->b->asXML() . '</textarea><br />' ;
echo
'<textarea rows="6" cols="40">' . subTree( $xml->b->asXML() , 'b' ) . '</textarea><br />' ;
?>
Anonymous
27-Aug-2008 03:50
DomDocument can do indentation on saveXML, so another way would be:

<?php

$simpleXml
= new SimpleXmlElement('...');

// ... do your simple xml construction

$dom = dom_import_simplexml($simpleXml)->ownerDocument;
$dom->formatOutput = true;

echo
$dom->saveXML();

?>

not especially better, and probably not faster, but an alternative.
Chris
27-Nov-2007 10:35
You habe to use utf8_encode() to insert your data into the XML-Object

<?php
$objXMLFile
= simplexml_load_string('<users></users>');
$objUser     = $objXMLFile->addChild('user');
$objUser->addAttribute('name', utf8_encode('Günther'));

echo
$objXMLFile->asXML();
?>
gary dot malcolm at gmail dot com
14-Sep-2007 07:15
I extended SimpleXml and added this code to give me pleasant source code XML.

<?php

   
public function asPrettyXML()
    {
       
$string = $this->asXML();
       
/**
         * put each element on it's own line
         */
       
$string =preg_replace("/>\s*</",">\n<",$string);

       
/**
         * each element to own array
         */
       
$xmlArray = explode("\n",$string);

       
/**
         * holds indentation
         */
       
$currIndent = 0;

       
/**
         * set xml element first by shifting of initial element
         */
       
$string = array_shift($xmlArray) . "\n";

        foreach(
$xmlArray as $element) {
           
/** find open only tags... add name to stack, and print to string
             * increment currIndent
             */

           
if (preg_match('/^<([\w])+[^>\/]*>$/U',$element)) {
               
$string .=  str_repeat(' ', $currIndent) . $element . "\n";
               
$currIndent += self::indent;
            }

           
/**
             * find standalone closures, decrement currindent, print to string
             */
           
elseif ( preg_match('/^<\/.+>$/',$element)) {
               
$currIndent -= self::indent;
               
$string .=  str_repeat(' ', $currIndent) . $element . "\n";
            }
           
/**
             * find open/closed tags on the same line print to string
             */
           
else {
               
$string .=  str_repeat(' ', $currIndent) . $element . "\n";
            }
        }

        return
$string;

    }
?>

Regards,

Gary Malcolm
Fred Trotter
23-Jun-2007 07:27
When trying to use the DOMDocument method for pretty printing the output of asXML be careful how you format the starting XML string. It cannot have spaces or other hidden chars "\n". I also had trouble with using different types of quotes for the starting XML, but I am unable to replicate that. So if you cannot get this to work then you might try swapping the single and double quotes.

<?php

$no_spaces
'<?xml version="1.0" encoding="UTF-8"?><Example></Example>';
$one_space '<?xml version="1.0" encoding="UTF-8"?><Example> </Example>';

echo
printy($no_spaces);
/* Outputs
<?xml version="1.0"?>
<Example>
 <poop from="Myself">
    <smell>stinky</smell>
  </poop>
</Example>
*/

echo printy($one_space);
/* Outputs... note the space...
<?xml version="1.0"?>
<Example> <poop from="Myself"><smell>stinky</smell></poop></Example>
*/

function printy($xmlstr){// a combination from the comments below...
$xml = new SimpleXMLElement($xmlstr);
$poop = $xml->addChild("poop");
$poop->addAttribute("from", "Myself");
$poop->addChild("smell", "stinky");
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$domnode = dom_import_simplexml($xml);
$domnode = $doc->importNode($domnode, true);
$domnode = $doc->appendChild($domnode);

return
$doc->saveXML();
}

?>
Blake W
12-May-2007 12:21
If your xml has already got a "\n" (new line) straight after the opening root tag, then the layout of the rest of the saveXML() will all be on one line, regardless of if you've set formatOutput to true. it's taken me about an hour to figure this out, and i hope this helps someone.
eggbird at bigfoot dot com
09-Apr-2007 05:39
One simple way to write out nicely indented XML data is by converting the whole batch to a DOM document, and using its formatOutput option:

<?php
$doc
= new DOMDocument('1.0');
$doc->formatOutput = true;
$domnode = dom_import_simplexml($some_simplexml_node);
$domnode = $doc->importNode($domnode, true);
$domnode = $doc->appendChild($domnode);

echo
$doc->saveXML();
?>
ShinnyLeather
06-Mar-2007 02:39
Awww snap. If you are to do something like this:

<?php

   
// ... You have already read an xml file into a SimpleXMLElement stored in variable $poop
   
$poop = $simpEle->addChild("poop");
   
$poop->addAttribute("from", "Myself");
   
$poop->addChild("smell", "stinky");
   
   
file_put_contents("xml.xml", $poop->asXML());

?>

It will add all of the new xml on one line

<poop from="Myself"><smell>stinky</smell></poop>

So when you look at what was originally a nicely tabbed out xml file, it looks like doof. I understand why this happens, so let me just say that it would be awesome if someone wrote and shared function that takes the asXML() string, parses it, and returns a nicely tabbed out version. As a lot of the XML files I work with are smaller than large, the benefit of having a file readable to the human eye far outweights the benefit of having a smaller filesize.

SimpleXMLElement::attributes> <SimpleXMLElement::addChild
Last updated: Fri, 13 Nov 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites