|
|
CI. SimpleXML functionsVarov�n� | Toto roz���en� je
EXPERIMENT�LN�. Chov�n� tohoto roz���en�,
n�zvy funkc� a v�echno ostatn�, co je zde zdokumentov�no, se v budouc�ch
verz�ch PHP m��e bez ohl�en� zm�nit. Berte to v �vahu a pou��vejte tento modul
na vlastn� nebezpe��. |
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.
This extension is only available if PHP was configured with
--enable-simplexml. The
PHP configuration script does this by default.
Pozn�mka:
This extension requires PHP 5.
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().
P��klad 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.
P��klad 2. Getting <plot>
<?php
include 'example.php';
$xml = simplexml_load_string($xmlstr);
echo $xml->movie[0]->plot; ?>
|
|
P��klad 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 = simplexml_load_string($xmlstr);
foreach ($xml->movie as $movie) {
echo $movie->plot, '<br />';
}
?>
|
|
P��klad 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 = simplexml_load_string($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;
}
}
?>
|
|
P��klad 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 = simplexml_load_string($xmlstr);
if ((string) $xml->movie->title == 'PHP: Behind the Parser') {
print 'My favorite movie.';
}
htmlentities((string) $xml->movie->title);
?>
|
|
P��klad 6. Using Xpath
SimpleXML includes builtin Xpath support.
To find all <character> elements:
<?php
include 'example.php';
$xml = simplexml_load_string($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.
|
P��klad 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 = simplexml_load_string($xmlstr);
$xml->movie[0]->actor[0]->age = '21';
echo $xml->asXML();
?>
|
The above code will output a new XML document, just like the original,
except that the new XML will define Ms. Coder's age as 21.
|
P��klad 8. 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
lajos dot arpasi at maxxlogic dot hu
08-Oct-2004 12:31
If you use PHP4 and miss the features of SimpleXML try MiniXML ().
MiniXML is a PHP class library for generating and parsing XML.
MiniXML have similar abilities like creating XML files from Arrays and importing XML files into Arrays.
You can manipulate the XML files more easily than SimpleXML.
It saved my life:).
04-Oct-2004 06:16
// The only way I found to add elements (through dom)
function & sXmlAddChildNode( $simpleXml, $xpathParentNode, $childNodeName, $childNodeValue='' ){
$dom = new DomDocument();
$dom->loadXML( $simpleXml->asXml() );
$xpath =& new DomXPath( $dom );
$parent =& $xpath->query( $xpathParentNode );
$elem =& $dom->createElement( $childNodeName, $childNodeValue );
$parent->item(0)->appendChild( $elem );
return simplexml_import_dom( $dom );
}
// usage:
$xml = simplexml_load_string( '<?xml version="1.0" standalone="yes"?><root><parenttag></parenttag></root>' );
$xml = sXmlAddChildNode( $xml, "//parenttag", 'childtag', 'xxxyyy' );
echo $xml->asXml();
majkqball_gmail_com
25-Sep-2004 10:44
Converting SimpleXML objects to an array:
<?php
$sx = simplexml_load_string('your xml string here');
function recursive_obj2array($obj, &$subject_array=array()) {
foreach ((array) $obj as $key => $var) {
if (is_object($var)) {
if(count((array) $var) == 0) {
$subject_array[$key] = 'NULL';
}
else {
recursive_obj2array($var, $subject_array[$key]);
}
}
else {
$subject_array[$key] = $var;
}
}
}
$gimmie = array();
recursive_obj2array($sx, $gimmie);
?>
Then $gimmie is foreach friendly.
Quick and dirty, but rather effective.
farzan ath ifarzan dod com
25-Sep-2004 10:38
You can access XML elements in a SimpleXML object using variables:
<?
$xml = simplexml_loaf_file(...);
print $xml->$element;
?>
or use functions:
<?
print $xml->{getLanguage()};
?>
Note: You Must use { and } or PHP would think you are calling a member function.
You can use members of other objects as well:
<?
print $xml->{$obj->var};
?>
As a real life example; I have used this statement in one of my projects:
<?
$x = $xrules->listing->fieldtitles->$lang->{$obj->name}->title;
?>
As you see, using varialbes and functions as element names are posible in SimpleXML; Thanks to PHP5's object orientaion new features.
jam from Russia
24-Sep-2004 03:23
Example:
<?xml version="1.0"?>
<root status="ok">
<login status="logining"/>
<user:name xmlns:user="">jam</user:name>
</root>
You can get value from "user:name" element:
$user_name = $xml->xpath('/root/user:name');
You can get value from "status" attribute "root" element:
$status = $xml->xpath('/root/@status');
You can get value from "status" attribute "login" element:
$logined = $xml->xpath('/root/login/@status');
SimpleXML work with namespace :-)
begemot at php dot com dot ua
03-Sep-2004 02:55
SimpleXML does not work with xml namespaces :-(
cellog at php dot net
31-Aug-2004 11:11
simplexml does not simply handle CDATA sections in a foreach loop.
<?php
$sx = simplexml_load_string('
<test>
<one>hi</one>
<two><![CDATA[stuff]]></two>
<t>
<for>two</for>
</t>
<multi>one</multi>
<multi>two</multi>
</test>');
foreach((array) $sx as $tagname => $val) {
if (is_string($val)) {
} elseif (is_array($val)) {
} elseif (is_object($val)) {
}
}
?>
To test in the loop, do this
<?php
if (count((array) $val) == 0) {
$val = '' . $val;
}
?>
bb at nospam xnull dot de
20-Jul-2004 10:39
the simplexml_to_array function below has a bug, if there are 2 or more fields, it get's bit out of control, here is the right one:
<?
function simplexml_to_array($xml) {
$ar = array();
foreach($xml->children() as $k => $v) {
$child = simplexml_to_array($v);
if( count($child) == 0 ) {
$child = (string)$v;
}
foreach( $v->attributes() as $ak => $av ) {
if( !is_array( $child ) ) {
$child = array( "value" => $child );
}
$child[$ak] = (string)$av;
}
if (!in_array($k,array_keys($ar))) {
$ar[$k] = $child;
} elseif (is_array($ar[$k][0])) {
$ar[$k][] = $child;
} else {
$ar[$k] = array($ar[$k]);
$ar[$k][] = $child;
}
}
return $ar;
}
?>
rishad at kaluma dot com
01-Jul-2004 04:12
To test whether a child node exists I used the following code:
<?php
function child_exists($xml, $childpath)
{
$result = $xml->xpath($childpath);
if (count($result)) {
return true;
} else {
return false;
}
}
?>
philip
17-Jun-2004 10:58
A introductory tutorial on simplexml can be found here:
*
*
*
Christophe VG
22-Apr-2004 07:34
The following function also takes in account the attributes. It treats them as if they where children.
<?php
function &simplexml_to_array($xml)
{
$ar = array();
foreach( $xml->children() as $k => $v ) {
$child = simplexml_to_array( $v );
if( count($child) == 0 ) {
$child = (string)$v;
}
foreach( $v->attributes() as $ak => $av ) {
if( !is_array( $child ) ) {
$child = array( "value" => $child );
}
$child[$ak] = (string)$av;
}
if( !in_array( $k, array_keys($ar) ) ) {
$ar[$k] = $child;
} else {
$ar[$k] = array( $ar[$k] );
$ar[$k][] = $child;
}
}
return $ar;
}
$xml = simplexml_load_string($xmlstr);
print_r( simplexml_to_array( $xml ) );
?>
The resulting array looks like this :
Array
(
[movie] => Array
(
[title] => PHP: Behind the Parser
[characters] => Array
(
...
)
I hope this can help someone. I needed this because you cannot put a simpleXML object into eg. a session due to serialization issues. This way I can store the information inside the XML document, eg. in a session, eliminating the need to reparse it time after time while still having a rather nice interface for accessing the data.
greg dot steffensen at spamless dot richmond dot edu
19-Feb-2004 11:04
Simplexml's simplicity can be deceptive. Simplexml elements behave either as objects or strings, depending on the context in which they're used (through overloading of the __toString() method, I assume). Statements implying conversion to string treat them as strings, while assignment operations treat them as objects. This can lead to unexpected behavior if, for example, you are trying to compare the values of two Simplexml elements. The expected syntax will not work. To force conversion to strings, just "typecast' whatever Simplexml element you're using. For example:
$s = simplexml_load_string('<foo>43</foo> <bar>43</bar>');
// Evaluates to false by comparing object IDs instead of strings
($s->foo == $s->bar);
// Evaluates to true
((string)$s->foo == (string)$s->bar);
[Ed. Note: Changed from quotes to casts because casts provide a quicker and more explicit conversion than do double quotes.]
| |