|
|
CXLVIII. SimpleXML functions
The SimpleXML extension provides a very simple and easily usable
toolset to convert XML to an object that can be processed with
normal property selectors and array iterators.
The SimpleXML extension requires PHP 5.
The SimpleXML extension is enabled by default. To disable it, use the
--disable-simplexml configure option.
Many examples in this reference require an XML string. Instead of
repeating this string in every example, we put it into a file which
we include in each example. This included file is shown in the
following example section. Alternatively, you could create an XML
document and read it with simplexml_load_file().
Пример 1. Include file example.php with XML string |
<?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;
?>
|
|
The simplicity of SimpleXML appears most clearly when one extracts
a string or number from a basic XML document.
Пример 2. Getting <plot> |
<?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);
echo $xml->movie[0]->plot; ?>
|
|
Пример 3. Accessing non-unique elements in SimpleXML
When multiple instances of an element exist as children of
a single parent element, normal iteration techniques apply.
|
<?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);
foreach ($xml->movie as $movie) {
echo $movie->plot, '<br />';
}
?>
|
|
Пример 4. Using attributes
So far, we have only covered the work of reading element names
and their values. SimpleXML can also access element attributes.
Access attributes of an element just as you would elements
of an array.
|
<?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);
foreach ($xml->movie[0]->rating as $rating) {
switch((string) $rating['type']) { case 'thumbs':
echo $rating, ' thumbs up';
break;
case 'stars':
echo $rating, ' stars';
break;
}
}
?>
|
|
Пример 5. Comparing Elements and Attributes with Text
To compare an element or attribute with a string or pass it into a
function that requires a string, you must cast it to a string using
(string). Otherwise, PHP treats the element as an object.
|
<?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);
if ((string) $xml->movie->title == 'PHP: Behind the Parser') {
print 'My favorite movie.';
}
htmlentities((string) $xml->movie->title);
?>
|
|
Пример 6. Using XPath
SimpleXML includes builtin XPath support.
To find all <character> elements:
|
<?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);
foreach ($xml->xpath('//character') as $character) {
echo $character->name, 'played by ', $character->actor, '<br />';
}
?>
|
'//' serves as a wildcard. To specify absolute
paths, omit one of the slashes.
|
Пример 7. Setting values
Data in SimpleXML doesn't have to be constant. The object allows
for manipulation of all of its elements.
|
<?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);
$xml->movie[0]->characters->character[0]->name = 'Miss Coder';
echo $xml->asXML();
?>
|
The above code will output a new XML document, just like the original,
except that the new XML will change Ms. Coder to Miss Coder.
|
Пример 8. Adding elements and attributes
Since PHP 5.1.3, SimpleXML has had the ability to easily add children and
attributes.
|
<?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);
$character = $xml->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');
$rating = $xml->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');
echo $xml->asXML();
?>
|
The above code will output an XML document based on the original but
having a new character and rating.
|
Пример 9. DOM Interoperability
PHP has a mechanism to convert XML nodes between SimpleXML
and DOM formats. This example shows how one might change
a DOM element to SimpleXML.
|
<?php
$dom = new domDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}
$s = simplexml_import_dom($dom);
echo $s->book[0]->title;
?>
|
|
add a note
User Contributed Notes
SimpleXML functions
David
30-Oct-2007 08: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.
lordi at msdi dot ca
23-Oct-2007 05: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.
~~
http://menic.info
28-Aug-2007 06: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.
cmsa at gmx dot de
27-Aug-2007 05: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
|
|