How about a recursive function to reduce the xml hard-coding in your apps? Here is my simple listing routine as an example:
<?php
function list_xml($str) {
$root = simplexml_load_string($str);
list_node($root);
}
function list_node($node) {
foreach ($node as $element) {
echo $element. "\n";
if ($element->children()) {
list_node($element);
echo "<br/>";
}
}
}
?>
simplexml_load_string
(PHP 5)
simplexml_load_string — XML 文字列をオブジェクトに代入する
説明
object simplexml_load_string
( string $data
[, string $class_name
[, int $options
[, string $ns
[, bool $is_prefix
]]]] )
整形式 XML 文字列をオブジェクトとして返します。
パラメータ
- data
-
整形式 XML 文字列。
- class_name
-
このオプションのパラメータを使用して、 simplexml_load_file() が指定されたクラスのオブジェクトを返すようにします。 このクラスは、SimpleXMLElement クラスを継承していなければなりません。
- options
-
PHP 5.1.0 と Libxml 2.6.0 から、追加の Libxml パラメータ を指定するために options を使用することもできます。
- ns
-
- is_prefix
-
返り値
SimpleXMLElement クラスのオブジェクトを返します。 XML ドキュメント内のデータをプロパティに含みます。 エラー時には FALSE を返します。
例
例1 XML 文字列をパースする
<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
<title>Forty What?</title>
<from>Joe</from>
<to>Jane</to>
<body>
I know that's the answer -- but what's the question?
</body>
</document>
XML;
$xml = simplexml_load_string($string);
var_dump($xml);
?>
上の例の出力は以下となります。
SimpleXMLElement Object ( [title] => Forty What? [from] => Joe [to] => Jane [body] => I know that's the answer -- but what's the question? )
この時点で、$xml->body のようにアクセスすることができます。
simplexml_load_string
Mark Omohundro, ajamyajax.com
04-Nov-2008 08:33
04-Nov-2008 08:33
javalc6 at gmail dot com
18-Oct-2008 04:25
18-Oct-2008 04:25
I wanted to convert an array containing strings and other arrays of the same type into a simplexml object.
Here is the code of the function array2xml that I've developed to perform this conversion. Please note that this code is simple without any checks.
<?php
function array2xml($array, $tag) {
function ia2xml($array) {
$xml="";
foreach ($array as $key=>$value) {
if (is_array($value)) {
$xml.="<$key>".ia2xml($value)."</$key>";
} else {
$xml.="<$key>".$value."</$key>";
}
}
return $xml;
}
return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>");
}
$test['type']='lunch';
$test['time']='12:30';
$test['menu']=array('entree'=>'salad', 'maincourse'=>'steak');
echo array2xml($test,"meal")->asXML();
?>
nospam at qool dot com
05-Jun-2008 09:45
05-Jun-2008 09:45
simplexml doesn't appear to like long attributes. I have tried passing it a valid xhtml document but the url in the anchor tag was causing simplexml to generate an error.
hattori at hanso dot com
16-Oct-2007 01:19
16-Oct-2007 01:19
Theres a problem with the below workaround when serializing fields containing html CDATA. For any other content type then HTML try to modfiy function parseCDATA.
Just add these lines before serializing.
This is also a workaround for this bug http://bugs.php.net/bug.php?id=42001
<?PHP
if(strpos($content, '<![CDATA[')) {
function parseCDATA($data) {
return htmlentities($data[1]);
}
$content = preg_replace_callback(
'#<!\[CDATA\[(.*)\]\]>#',
'parseCDATA',
str_replace("\n", " ", $content)
);
}
?>
hattori at hanso dot com
17-Sep-2007 12:15
17-Sep-2007 12:15
If you want to serialize and unserialize SimpleXMLElement objects for caching, you need to transform the SimpleXMLElement object into a standard class object before unserializing.
This is only if you want to cache converted data, the functionallity of the SimpleXMLElement will not be held.
$content = '<SomeXML....'
$serialized = str_replace(
array('O:16:"SimpleXMLElement":0:{}', 'O:16:"SimpleXMLElement":'),
array('s:0:"";', 'O:8:"stdClass":'),
serialize(simplexml_load_string($content))
);
$unserialized = unserialize($serialized);
nbijnens at servs dot eu
10-Sep-2007 03:17
10-Sep-2007 03:17
Please note that not all LIBXML options are supported with the options argument.
For instance LIBXML_XINCLUDE does not work. But there is however a work around:
<?php
$xml = new DOMDocument();
$xml->loadXML ($XMLString);
$xml->xinclude();
$xml = simplexml_import_dom($xml);
?>
Pedro
06-Jul-2007 11:28
06-Jul-2007 11:28
Attention:
simplexml_load_string has a problem with entities other than (<, >, &, " and ').
Use numeric character references instead!
youx_free_fr
23-May-2007 07:52
23-May-2007 07:52
While needing to add an xml subtree to an existing simplexml object, I noticed that simplexml_load_string fails with strings like
<emptynode></emptynode>
I needed to use dom instead of simplexml to bypass this problem and work with any kind of xml strings.
David Somerset
08-May-2007 09:39
08-May-2007 09:39
Another option for having simplexml convert CDATA into plain text is to simply type cast the result to string. Here's an example:
$xmlRoot = simplexml_load_string('<?xml version="1.0"?>
<tvshows>
<show>
<name>The Simpsons</name>
</show>
<show>
<name><![CDATA[Lois & Clark]]></name>
</show>
</tvshows>');
$show = array();
foreach($xmlRoot as $val){
$show[] = (string) $val->name;
}
php at teamhirsch dot com
25-Apr-2007 12:46
25-Apr-2007 12:46
It's worth noting that in the example above, $xml->body will actually return an object of type SimpleXMLElement, not a string, e.g.
SimpleXMLElement Object (
[0] => this is the text in the body tag
)
If you want to get a string out of it you must explicitly cast it using (string) or double quotes, or pass $xml->body (or whatever attribute you want to access) to any function that returns a string, such as urldecode() or trim().
m dot ament at mailcity dot com
06-Mar-2007 04:51
06-Mar-2007 04:51
Warning:
The parsing of XML-data will stop when reaching character 0.
Please avoid this character in your XML-data.
mindpower
30-Jan-2007 01:03
30-Jan-2007 01:03
A simple extension that adds a method for retrieving a specific attribute:
<?php
class simple_xml_extended extends SimpleXMLElement
{
public function Attribute($name)
{
foreach($this->Attributes() as $key=>$val)
{
if($key == $name)
return (string)$val;
}
}
}
$xml = simplexml_load_string('
<xml>
<dog type="poodle" owner="Mrs Smith">Rover</dog>
</xml>', 'simple_xml_extended');
echo $xml->dog->Attribute('type');
?>
outputs 'poodle'
I prefer to use this technique rather than typecasting attributes.
h
15-Nov-2006 08:44
15-Nov-2006 08:44
seems like simplexml has a line-length restriction - fails if a largeish XML doc with no linebreaks is passed as a string or file.
h
paul at santasoft dot com
25-Jul-2006 06:22
25-Jul-2006 06:22
If you have PHP > 5.1 and LibXML > 2.6, use this function call to have simplexml convert CDATA into plain text.
simplexml_load_string($xmlstring, 'SimpleXMLElement', LIBXML_NOCDATA);
Too bad, so sad with PHP < 5.1.
