|
użytkowników online: 59
|
OPINIE UŻYTKOWNIKÓW
|
W takich dniach, jak ten, nie żałuję, że wykupiłem abonament. Korzystam z porad na tych stronach nawet kilkanaście razy w tygodniu i dzięki nim prace nad stronami dla klientów idą mi o wiele szybciej, a strony wyglądają bardziej profesjonalnie. Nie wiem, jak mogłem wcześniej pracować bez dostępu do porad w tym serwisie!
Wojciech Miszkiewicz
|
|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
CXIII. 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().
Przykład 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.
Przykład 2. Getting <plot> |
<?php
include 'example.php';
$xml = simplexml_load_string($xmlstr);
echo $xml->movie[0]->plot; ?>
|
|
Przykład 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 />';
}
?>
|
|
Przykład 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;
}
}
?>
|
|
Przykład 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);
?>
|
|
Przykład 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.
|
Przykład 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]->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.
|
Przykład 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;
?>
|
|
User Contributed NotesJason
28-Jan-2006 03:45
As noted by paul at preinheimer dot com in a lower note ( http://us3.php.net/manual/en/ref.simplexml.php#52583 );
If you want to access an element that has a dash in its name, (as is common with the XML documents provided by the Library of Congress, as well as the NWS) you will need to handle it a little bit differently.
You can either use XPATH, which works fine, but will return an array of results every time, even if there is a single result.
eg.
$xml->xpath('/data/time-layout/start-valid-time'}
You can also choose just to encapsulate the element names containing a dash:
$xml->data->{'time-layout'}->{'start-valid-time'}
greyl at greyworld dot net
16-Jan-2006 07:56
If you want to use XML elements containing a '-', you can use a variable:
<?php
$xml = simplexml_load_file("test.xml");
$tag = 'first-name';
echo $xml->$tag->asxml();
?>
12-Jan-2006 08:14
Note that xml elements cannot contain a '-'.
The following 2 print function calls will fail!
<?php
if (!file_exists('test.xml')) {
exit('Failed to open galadhrim.xml.');
}
$xml = simplexml_load_file("text.xml");
print($xml->first-name);
print($xml->sur-name);
?>
t at wantzen dot com
17-Oct-2005 11:00
Thanks to Daniel Faivre! Great work!
I modified it to an array filled with ISO-8859-1 text and not UTF-8. Haven't tested it in detail - so be cautious!
Tobias
<?php
function simplexml2ISOarray($xml) {
if (get_class($xml) == 'SimpleXMLElement') {
$attributes = $xml->attributes();
foreach($attributes as $k=>$v) {
if ($v) $a[$k] = (string) $v;
}
$x = $xml;
$xml = get_object_vars($xml);
}
if (is_array($xml)) {
if (count($xml) == 0) return (string) $x; foreach($xml as $key=>$value) {
$r[$key] = simplexml2ISOarray($value);
if ( !is_array( $r[$key] ) ) $r[$key] = utf8_decode( $r[$key] );
}
if (isset($a)) $r['@'] = $a; return $r;
}
return (string) $xml;
}
?>
js1 at qq dot com (js5131)
12-Oct-2005 03:27
modify the content of simpleXML:
<?php
$str="<?xml version='1.0'?>
<root>
<name>tom</name>
<sex>man</sex>
</root>";
$sx = simplexml_load_string($str);
$sx -> name = "simpleXML";
echo $sx->asxml();
?>
lists at cyberlot dot net
07-Sep-2005 09:51
While you can't add new elements to a SimpleXML object you can however add new attributes
<?php
$string = '<doc channel="chat"><test1>Hello</test1></doc>';
$xml = simplexml_load_string($string);
$xml->test1['sub'] = 'No';
echo $xml->asXML();
?>
Will return output
<doc channel="chat"><test1 sub="No">Hello</test1></doc>
galaxiaguy at hotmail dot com
03-Sep-2005 04:52
I tried extending SimpleXMLElement to add some functionality and found you can't set new properties. I assume this is something to do with built-in magic methods or something.
So I wrote a class that behaves the same as SimpleXMLElement (by delegating most of it's work) but is arbitrarily extendable.
http://www.oliverbrown.me.uk/2005/09/03/extending-simplexml/
It's very new and not very well tested but could be useful to somebody.
mmacadams at casslin dot com
02-Sep-2005 06:46
it's important to note that PHP seems to disregard to first "all encompassing" tag...
for example:
$xmlstr="<order>
<billing_name>Matt</billing_name>
<billing_address>123 Main St.</billing_address>
</order>";
the 'billing_name' would be accessed by:
$xml = simplexml_load_string($xmlstr);
$billing_name = $xml->billing_name;
NOT:
$xml = simplexml_load_string($xml);
$billing_name = $xml->order->billing_name;
Maybe I'm just an idiot, but this took me a few hours to figure out.. (Partly due to the similiarity between the words "movie" and "movies" in the Movie example at the top of the page)
haha
hope this helps save someone some time! :)
15-Jul-2005 12:53
Testing if an element has attributes is a little fuzzy, and I haven't got a solution.
isset returns true on [0], empty returns false.
trying to echo $xml->element[0] gives nothing as an output.
but that occurs even if it has at least one argument, so you can't access them with $xml->element[0].
emdeboas at bronstee dot com
30-Jun-2005 12:51
It seems not to be possible to find the name of the first XML tag in a SimpleXML document. Therefore here a simple way to find out (using the example XML):
<?php
include 'example.php';
$xml = simplexml_load_string($xmlstr);
$dom = dom_import_simplexml ($xml);
$root = $dom->tagName;
echo "-- the tagname is...: $root<br/>"; ?>
Maciek Ruckgaber <maciekrb at gmai dot com>
08-Jun-2005 02:07
after wondering around some time, i just realized something (maybe obvious, not very much for me). Hope helps someone to not waste time as i did :-P
when you have something like:
$xmlstr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<double xmlns="http://foosite.foo/">2328</double>
XML;
you will have the simpleXML object "transformed" to the text() content:
$xml = simplexml_load_string($xmlstr);
echo $xml; // this will echo 2328 (string)
cyberlot at cyberlot dot net
09-May-2005 10:24
outping a SimpleXML object is deceptive
For example
<doc channel="chat"><mess>Hello</mess></doc>
print_r returns
SimpleXMLElement Object
(
[mess] => Hello
)
One might assume you are "losing" the attribute of doc BUT
echo $object['channel']
Does return the value of chat
No xpath /doc/@channel mess needed to access it, Its there you just can't "see" it until you access it directly
Everything is there, sometimes you just have to hunt for it.
paul at preinheimer dot com
06-May-2005 02:11
Hi,
If you want to access an element that has a dash in its name, (as is common with the XML documents provided by the Library of Congress, as well as the NWS) you will need to handle it a little bit differently.
You can either use XPATH, which works fine, but will return an array of results every time, even if there is a single result.
eg.
$xml->xpath('/data/time-layout/start-valid-time'}
You can also choose just to encapsulate the element names containing a dash:
$xml->data->{'time-layout'}->{'start-valid-time'}
--
On a only partially related note, dealing with SimpleXML is one of the only times I have employed casting with PHP. While iterating (foreach) through the valid times, echo'ing the element worked great (it merely echo'ed the apropriate time), assigning it to another variable resulted in a SimpleXML object containing the time to be assigned, rather than just the time itself. This was resolved by casting the time to a string:
foreach($xml->data->{'time-layout'}->{'start-valid-time'} AS $time)
{
$weatherDates[] = (string) $time;
}
T CHASSAGNETTE t_chassagnette at yahoo dot fr
04-May-2005 10:57
Another method to parse an XML Document into a PHP array with SIMPLEXML inspired from Daniel FAIVRE !
function xml2php($xml)
{
$fils = 0;
$tab = false;
$array = array();
foreach($xml->children() as $key => $value)
{
$child = xml2php($value);
//To deal with the attributes
foreach($node->attributes() as $ak=>$av)
{
$child[$ak] = (string)$av;
}
//Let see if the new child is not in the array
if($tab==false && in_array($key,array_keys($array)))
{
//If this element is already in the array we will create an indexed array
$tmp = $array[$key];
$array[$key] = NULL;
$array[$key][] = $tmp;
$array[$key][] = $child;
$tab = true;
}
elseif($tab == true)
{
//Add an element in an existing array
$array[$key][] = $child;
}
else
{
//Add a simple element
$array[$key] = $child;
}
$fils++;
}
if($fils==0)
{
return (string)$xml;
}
return $array;
}
nelson_menezes at yahoo dot co dot uk
01-Mar-2005 02:05
Note that SimpleXML expects to both read and output XML in UTF-8 encoding. You'll need to add a line such as this at the top of your input XML file if it isn't saved in UTF-8 (adjust to whatever encoding used):
<?xml version="1.0" encoding="ISO-8859-1" ?>
On the output side of things, if you're not serving/handling UTF-8, you'll need to use utf8_decode() [red. but that will only work for ISO-8859-1, not other encodings]. Common mistake: http://bugs.php.net/bug.php?id=28154
webmarks
14-Feb-2005 06:57
I'm new to PHP and XML, but I think others might pull their hair out over this too. I forgot about XML and whitespace when I was populating an array with node values, and was getting what appeared to be duplicate values despite using array_unique(). Use trim() when populating an array or assigning a variable.
<?php
$xml_array = array();
foreach ($resource->xpath($node_match) as $option){
$xml_array[$i] = trim($option);
$i++;
}
$xml_unique_array = array_unique($xml_array);
?>
roland dot swingler at transversal dot com
08-Feb-2005 11:24
Just a quick note - if you wish to get the name of the tag you are operating on, use the the key bit of foreach, i.e in the example:
<?php
foreach($xml->movie[0]->children() as $tag => $child){
echo $tag;
}
?>
This might seem obvious but it stumped me for a bit.
Daniel FAIVRE - geomaticien.com
15-Jan-2005 12:46
I've searched a while for a convenient "to array" function, and finally wrote it. These one provide at least 5 cool features:
- the MOST IMPORTANT: return a correct structure when several childs nodes have the same name: nodes are numbered properly
- read CDATA values
- returned array is very easy-to-use
- attributes returned in sub-arrays with key [@]
- very fast
When you create a "xml2array" function, you need to manage nodes with attributes, but without children: i've choosed to ignore their attributes to avoid a "virtual ['value'] node" for such nodes in the returned array.
<?php
function simplexml2array($xml) {
if (get_class($xml) == 'SimpleXMLElement') {
$attributes = $xml->attributes();
foreach($attributes as $k=>$v) {
if ($v) $a[$k] = (string) $v;
}
$x = $xml;
$xml = get_object_vars($xml);
}
if (is_array($xml)) {
if (count($xml) == 0) return (string) $x; foreach($xml as $key=>$value) {
$r[$key] = simplexml2array($value);
}
if (isset($a)) $r['@'] = $a; return $r;
}
return (string) $xml;
}
?>
igor kraus
07-Jan-2005 07:37
A simple way to merge two SimpleXML objects.
<?php
function simplexml_merge (SimpleXMLElement &$xml1, SimpleXMLElement $xml2)
{
$dom1 = new DomDocument();
$dom2 = new DomDocument();
$dom1->loadXML($xml1->asXML());
$dom2->loadXML($xml2->asXML());
$xpath = new domXPath($dom2);
$xpathQuery = $xpath->query('/*/*');
for ($i = 0; $i < $xpathQuery->length; $i++)
{
$dom1->documentElement->appendChild(
$dom1->importNode($xpathQuery->item($i), true));
}
$xml1 = simplexml_import_dom($dom1);
}
$xml1 = simplexml_load_string('<root><child>child 1</child></root>');
$xml2 = simplexml_load_string('<root><child>child 2</child></root>');
simplexml_merge($xml1, $xml2);
echo($xml1->asXml());
?>
Will output:
<?xml version="1.0"?>
<root>
<child>child 1</child>
<child>child 2</child>
</root>
brcavanagh AT NO SPAM hotmail.com
03-Jan-2005 06:18
If you are looking to use SimpleXML for anything but reading XML documents, you should really reconsider, and use the XML DOM library. By the time you get enough utilities implemented in DOM to handle all the set backs in SimpleXML, you will have defeated the purpose of using SimpleXML. There are a few reasons for this, and there are already many workrounds, but the primairy issues are this
1) No complex node assignment. You cannot switch nodes or replace them.
2) No appending new child nodes
3) Whenever you do something like $new_node = $xml_doc->node you will always get a reference even if you use a clone method, which will crash the script.
Other than that, its a great tool for reading docs.
aidan at php dot net
24-Dec-2004 09:42
lajos dot arpasi at maxxlogic dot hu
08-Oct-2004 02:31
If you use PHP4 and miss the features of SimpleXML try MiniXML (http://minixml.psychogenic.com).
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:).
jam from Russia
24-Sep-2004 05:23
Example:
<?xml version="1.0"?>
<root status="ok">
<login status="logining"/>
<user:name xmlns:user="http://user.com/">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 :-)
cellog at php dot net
01-Sep-2004 01: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;
}
?>
rishad at kaluma dot com
01-Jul-2004 06: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
18-Jun-2004 12:58
greg dot steffensen at spamless dot richmond dot edu
20-Feb-2004 12: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:
<?php
$s = simplexml_load_string('<foo>43</foo> <bar>43</bar>');
($s->foo == $s->bar);
((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.]
|