<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>@blog.justoneplanet.info &#187; XML</title>
	<atom:link href="http://blog.justoneplanet.info/category/computer-language/php/xml/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.justoneplanet.info</link>
	<description>日々勉強</description>
	<lastBuildDate>Wed, 08 Feb 2012 02:57:17 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>PHP SOAP and REST at Web Service（ウェブサービスでのSOAPとREST）</title>
		<link>http://blog.justoneplanet.info/2009/05/22/php-soap-and-rest-at-web-service%ef%bc%88%e3%82%a6%e3%82%a7%e3%83%96%e3%82%b5%e3%83%bc%e3%83%93%e3%82%b9%e3%81%a7%e3%81%aesoap%e3%81%a8rest%ef%bc%89/</link>
		<comments>http://blog.justoneplanet.info/2009/05/22/php-soap-and-rest-at-web-service%ef%bc%88%e3%82%a6%e3%82%a7%e3%83%96%e3%82%b5%e3%83%bc%e3%83%93%e3%82%b9%e3%81%a7%e3%81%aesoap%e3%81%a8rest%ef%bc%89/#comments</comments>
		<pubDate>Fri, 22 May 2009 04:58:56 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://blog.justoneplanet.info/?p=1261</guid>
		<description><![CDATA[■SOAP 自サーバにない（所有していない）プログラムのメソッドを呼び出す、リモートプロシージャコール（遠隔呼び出し）のためのプロトコル。相手側がアクセス可能にしているメソッドならばアクセスが可能である。但し、PHPでS [...]]]></description>
			<content:encoded><![CDATA[<h3>■SOAP</h3>
<p>自サーバにない（所有していない）プログラムのメソッドを呼び出す、リモートプロシージャコール（遠隔呼び出し）のためのプロトコル。相手側がアクセス可能にしているメソッドならばアクセスが可能である。但し、PHPでSOAPを使用するには、インストール時に&#8211;enable-soapされていなければならない。</p>
<h4>ウェブサービスへのアクセス</h4>
<p>以下のようにするとGoogle検索のウェブサービスを利用することができる。</p>
<pre class="brush: php;">
&lt;?php
try {
    $client = new SoapClient('http://api.google.com/GoogleSearch.wsdl');
    $results = $client-&gt;doGoogleSearch($key, $query, 0, 10, false, '', false, '', '', '');
    foreach($results-&gt;resultElements as $result){
        print('&lt;a href=&quot;&gt;' . htmlentities($result-&gt;URL, ENT_QUOTES) . '&quot;&gt;');
        print(htmlentities($result-&gt;title, ENT_COMPAT));
        print('&lt;/a&gt;');
    }
}
catch(SoapFault $e){
    $e-&gt;getMessage();
}
?&gt;
</pre>
<div class="kakomi">
<h5>SoapClientについて</h5>
<ul>
<li>Googleに提供されたWSDLファイルに基づきSOAPクライアントを生成する</li>
<li>SoapClientは失敗すると例外をスローする</li>
</ul>
<h5>WSDLについて</h5>
<ul>
<li>WSDLファイルとは、「提供されている場所」や「メッセージの形式」「プロトコル」「メソッド」など、サービスの具体的内容が記述されている</li>
<li>WSDLファイルを使用しない場合は、SoapClientの第一引数にnullを、第二引数でウェブサービスのエントリーポイントのURIを指定しなければならない</li>
</ul>
</div>
<h4>デバッグ</h4>
<p>SOAPクライアントは、SOAPサーバに送受信したメッセージを用いてデバッグするために特別なメソッドを備えている。但し、使用するためにはSoapClientの第二引数でtraceを1に設定しなければならない。以下のようにすると、生の通信を見ることができる。</p>
<pre class="brush: php;">
&lt;?php
$cleint = new SoapClient(
    'http://api.google.com/GoogleSearch.wsdl',
    array(
        'trace' =&gt; 1
    )
);
$results = $client-&gt;doGoogleSearch($key, $query, 0, 10, false, '', false, '', '', '');
print($results-&gt;__getLastRequestHeaders());
print($result-&gt;__getLastRequest());
/*
POST /search/beta2 HTTP/1.1
Host: api.google.com
Connection: Keep-Alive
User-Agent: PHP SOAP 0.1
Connect-Type: text/xml; charset=utf-8
SOAPAction: &quot;url:GoogleSearchAction&quot;
Content-Length: 900

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
...

*/
?&gt;
</pre>
<h4>SOAPサーバの作り方</h4>
<p>以下のように、SOAPサーバの挙動を定義する。</p>
<pre class="brush: php;">
&lt;?php
class MySoapServer {
    public function getMessage(){
        return 'Hello, World!';
    }
    public function addNumbers($num1, $num2){
        return (int)$num1 + (int)$num2;
    }
}
?&gt;
</pre>
<p>以下のように、定義したクラスを実際にSoapServerとして設定する。</p>
<pre class="brush: php;">
&lt;?php
require_once('MySoapServer.class.php');
$server = new SoapServer(
    null,
    array(
        'uri' =&gt; 'http://sample.org/soap/server'
    )
);
$server-&gt;setClass('MySoapServer');
$server-&gt;handle();
?&gt;
</pre>
<p>以上のような場合、クライアント側のコードは以下のようになる。</p>
<pre class="brush: php;">
&lt;?php
$client = new SoapClient(
    null,
    array(
        'location' =&gt; 'http://sample.org/soap/server/server.php',
        'uri'        =&gt; 'http://sample.org/soap/server/',
    )
);
print($client-&gt;getMessage());//Hello, World!
print($client-&gt;addNumbers(1,8));//9
?&gt;
</pre>
<h3>■REST</h3>
<p>RESTはプロトコルではなく、ウェブサービスの設計思想の一つである。個々のリソースはURIにおいて参照することができる。</p>
<pre class="brush: php;">
&lt;?php
$user = 'john';
$pass = 'password';
$tag = htmlentities($_POST['tag'], ENT_QUOTES);
$req = &quot;https://{$user}:{$pass}@api.del.icio.us/v1/posts/all?tag={$tag}&quot;;

$bookmarks = new SimpleXMLElement($req, null, true);
foreach($bookmarks as $bookmark){
    print('&lt;a href=&quot;' . htmlentities($bookmark['href'], ENT_QUOTES) . '&quot;&gt;');
    print(htmlentities($bookmark['description'], ENT_COMPAT));
    print('&lt;/a&gt;');
}
?&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.justoneplanet.info/2009/05/22/php-soap-and-rest-at-web-service%ef%bc%88%e3%82%a6%e3%82%a7%e3%83%96%e3%82%b5%e3%83%bc%e3%83%93%e3%82%b9%e3%81%a7%e3%81%aesoap%e3%81%a8rest%ef%bc%89/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP DOM</title>
		<link>http://blog.justoneplanet.info/2009/05/19/php-dom/</link>
		<comments>http://blog.justoneplanet.info/2009/05/19/php-dom/#comments</comments>
		<pubDate>Tue, 19 May 2009 14:19:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://blog.justoneplanet.info/?p=1243</guid>
		<description><![CDATA[以下のXMLを使用してサンプルコードを解説する。 &#60;?xml version=&#34;1.0&#34;?&#62; &#60;library xmlns:lib=&#34;http://sample.com/l [...]]]></description>
			<content:encoded><![CDATA[<p>以下のXMLを使用してサンプルコードを解説する。</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;library xmlns:lib=&quot;http://sample.com/library&quot;&gt;
    &lt;book isbn=&quot;0111222333&quot;&gt;
        &lt;lib:title&gt;She sells seashells&lt;/lib:title&gt;
        &lt;author&gt;Emily&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;0123456789&quot;&gt;
        &lt;title&gt;Eight apes ate eight apples&lt;/title&gt;
        &lt;author&gt;John&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;9876543210&quot;&gt;
        &lt;title&gt;Strike&lt;/title&gt;
        &lt;author&gt;Mike&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;1234567890&quot;&gt;
        &lt;title&gt;Shine&lt;/title&gt;
        &lt;author&gt;Jack&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
&lt;/library&gt;
</pre>
<h3>■読込</h3>
<h4>ファイルパスを指定</h4>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;load('test.xml');
?&gt;
</pre>
<h4>文字列をDOMとして読込</h4>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;loadXML($str);
?&gt;
</pre>
<h4>HTMLファイルとして読込</h4>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;loadHTMLFile('test.html');
?&gt;
</pre>
<h4>HTMLとして読込</h4>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;loadHTML($str);
?&gt;
</pre>
<div class="kakomi">
<h4>各メソッドについて</h4>
<table>
<tr>
<th></th>
<th>ファイルからの読込</th>
<th>文字列からの読込</th>
</tr>
<tr>
<th>XML</th>
<td>DomDocument::load</td>
<td>DomDocument::loadXML</td>
</tr>
<tr>
<th>HTML</th>
<td>DomDocument::loadHTMLFile</td>
<td>DomDocument::loadHTML</td>
</tr>
</table>
</div>
<h3>■保存</h3>
<h4>ファイルへの保存</h4>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;load('test.xml');
if($is_xhtml){
    $dom-&gt;save('test.xml');
}
else{
    $dom-&gt;saveHTMLFile('test.html');
}
?&gt;
</pre>
<h4>データとして格納</h4>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;load('test.xml');
if($is_xhtml){
    $data = $dom-&gt;saveXML();
}
else{
    $data = $dom-&gt;saveHTML();
}
?&gt;
</pre>
<div class="kakomi">
<h4>各メソッドについて</h4>
<table>
<tr>
<th></th>
<th>ファイルに保存</th>
<th>データとして返す</th>
</tr>
<tr>
<th>XML</th>
<td>DomDocument::save</td>
<td>DomDocument::saveXML</td>
</tr>
<tr>
<th>HTML</th>
<td>DomDocument::saveHTMLFile</td>
<td>DomDocument::saveHTML</td>
</tr>
</table>
</div>
<h3>■DOMにおけるXPath</h3>
<p>以下のようにDomXPathオブジェクトを通して、DomDocumentオブジェクトに対するxpathを実行する。</p>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;load('test.xml');
$xpath = new DomXPath($dom);
$result = $xpath-&gt;query('/library/book/title/text()');
foreach($result as $title){
    print($title-&gt;data);
}
/*
Eight apes ate eight apples
Strike
Shine
*/
?&gt;
</pre>
<p>以下のように、名前空間を使うこともできる。</p>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;load('test.xml');
$xpath = new DomXPath($dom);
$xpath-&gt;registerNamespace('lib', 'http://sample.com/library');
$result = $xpath-&gt;query('//lib:title/text()');
foreach($result as $book){
    print($book-&gt;data);
}
/*
She sells seashells
*/
?&gt;
</pre>
<h3>■XMLドキュメントの操作</h3>
<p>以下のようにして、要素を追加することができる。documentElementはドキュメントのルートの要素を示す。</p>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;load('test.xml');

$book = $dom-&gt;createElement('book');
$book-&gt;setAttribute('isbn', '0123456789');

$title = $dom-&gt;createElement('title');
$txt = $dom-&gt;createTextNode('PHP');

$title-&gt;appendChild($txt);
$book-&gt;appendChild($title);

$author = $dom-&gt;createElement('author', 'Jane');
$book-&gt;appendChild($author);

$publisher = $dom-&gt;createElement('publisher', 'amazon');
$book-&gt;appendChild($publisher);

$dom-&gt;documentElement-&gt;appendChild($book);
/*
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;library&gt;
    &lt;book isbn=&quot;0111222333&quot;&gt;
        &lt;title&gt;She sells seashells&lt;/title&gt;
        &lt;author&gt;Emily&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;0123456789&quot;&gt;
        &lt;title&gt;Eight apes ate eight apples&lt;/title&gt;
        &lt;author&gt;John&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;9876543210&quot;&gt;
        &lt;title&gt;Strike&lt;/title&gt;
        &lt;author&gt;Mike&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;1234567890&quot;&gt;
        &lt;title&gt;Shine&lt;/title&gt;
        &lt;author&gt;Jack&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
&lt;book isbn=&quot;0123456789&quot;&gt;&lt;title&gt;PHP&lt;/title&gt;&lt;author&gt;Jane&lt;/author&gt;&lt;publisher&gt;amazon&lt;/publisher&gt;&lt;/book&gt;&lt;/library&gt;
*/
?&gt;
</pre>
<div class="kakomi">
<h4>各メソッドについて</h4>
<dl>
<dt>DomElement <strong>DomDocument::createElement</strong>(string $name[, string $value])</dt>
<dd>新しい要素ノードを生成する。第二引数で要素の値を指定することもできる</dd>
<dt>DomAttr <strong>DomElement::setAttribute</strong>(string $name, string $value)</dt>
<dd>新しい属性を追加する</dd>
<dt>DomNode <strong>DomNode::appendChild</strong>(DomNode $node)</dt>
<dd>子要素を追加する</dd>
<dt>DomText <strong>DomNode::createTextNode</strong>(string $content)</dt>
<dd>新しいテキストノードを生成する</dd>
</dl>
<p>個人的にこのあたりはJavaScriptで馴染んでいるので覚えやすい。</p>
</div>
<h3>■要素の移動</h3>
<p>特定の要素の前に移動する場合は、以下のようにDomNode::insertBeforeメソッドを使用する。</p>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;load('test.xml');
$xpath = new DomXPath($dom);
$result = $xpath-&gt;query('/library/book');
$xpath-&gt;item(1)-&gt;paentNode-&gt;insertBefore($result-&gt;item(1), $result-&gt;item(0));
print($dom-&gt;saveXML());
/*
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;library&gt;
    &lt;book isbn=&quot;0123456789&quot;&gt;
        &lt;title&gt;Eight apes ate eight apples&lt;/title&gt;
        &lt;author&gt;John&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;0111222333&quot;&gt;
        &lt;title&gt;She sells seashells&lt;/title&gt;
        &lt;author&gt;Emily&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;9876543210&quot;&gt;
        &lt;title&gt;Strike&lt;/title&gt;
        &lt;author&gt;Mike&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;1234567890&quot;&gt;
        &lt;title&gt;Shine&lt;/title&gt;
        &lt;author&gt;Jack&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
&lt;/library&gt;
*/
?&gt;
</pre>
<p>要素の最後尾に移動する場合は、以下のようにDomNode::appendChildメソッドを使用する。</p>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;load('test.xml');

$xpath = new DomXPath($dom);
$result = $xpath-&gt;query('/library/book');
$result-&gt;item(1)-&gt;parentNode-&gt;appendChild($result-&gt;item(0));
print($dom-&gt;saveXML());
/*
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;library&gt;
    &lt;book isbn=&quot;0123456789&quot;&gt;
        &lt;title&gt;Eight apes ate eight apples&lt;/title&gt;
        &lt;author&gt;John&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;9876543210&quot;&gt;
        &lt;title&gt;Strike&lt;/title&gt;
        &lt;author&gt;Mike&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;1234567890&quot;&gt;
        &lt;title&gt;Shine&lt;/title&gt;
        &lt;author&gt;Jack&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;0111222333&quot;&gt;
        &lt;title&gt;She sells seashells&lt;/title&gt;
        &lt;author&gt;Emily&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
&lt;/library&gt;
*/
?&gt;
</pre>
<p>但し、上述のメソッドはノードをコピーしない。従って、複製を挿入したい場合は、DomNode::cloneNodeメソッドを使用し、複製してから挿入しなければならない。</p>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;load('test.xml');

$xpath = new DomXPath($dom);

$result = $xpath-&gt;query('/library/book');
$elm = $result-&gt;item(0)-&gt;cloneNode();
$result-&gt;item(1)-&gt;parentNode-&gt;appendChild($elm);
print($dom-&gt;saveXML());
/*
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;library&gt;
    &lt;book isbn=&quot;0111222333&quot;&gt;
        &lt;title&gt;She sells seashells&lt;/title&gt;
        &lt;author&gt;Emily&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;0123456789&quot;&gt;

        &lt;title&gt;Eight apes ate eight apples&lt;/title&gt;
        &lt;author&gt;John&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;9876543210&quot;&gt;
        &lt;title&gt;Strike&lt;/title&gt;
        &lt;author&gt;Mike&lt;/author&gt;

        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;1234567890&quot;&gt;
        &lt;title&gt;Shine&lt;/title&gt;
        &lt;author&gt;Jack&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;

&lt;book isbn=&quot;0111222333&quot;/&gt;&lt;/library&gt;
*/
?&gt;
</pre>
<div class="kakomi">
<h4>各メソッドについて</h4>
<dl>
<dt>DomNode <strong>DomNode::insertBefore</strong>(DomNode $node[, DomNode $refnode])</dt>
<dd>第一引数で指定したノードが、第二引数で指定したノードの前に挿入される。</dd>
<dt>DomNode <strong>DomNode::appendChild</strong>(DomNode $node)</dt>
<dd>DomNodeの最後尾に、引数で指定したノードを挿入する。</dd>
<dt>DomNode <strong>DomNode::cloneNode</strong>(bool $recursive=false)</dt>
<dd>DomNodeを複製する。引数にtrueを指定すると子ノードまで含めた複製が生成される。デフォルトはfalse。</dd>
</dl>
</div>
<h3>■要素の削除</h3>
<p>要素を削除するには、以下のようにDomNode::removeChildメソッドを使用する。また、属性を削除するには、DomNode::removeAttributeメソッド使用する。さらに、要素内のテキストを削除したい場合は、DomCharacterData::deleteDataメソッドを使用する。</p>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;load('test.xml');

$xpath = new DomXPath($dom);
$result = $xpath-&gt;query('/library/book');

$result-&gt;item(0)-&gt;parentNode-&gt;removeChild($result-&gt;item(0));
$result-&gt;item(1)-&gt;removeAttribute('isbn');

$result = $xpath-&gt;query('/library/book/publisher/text()');
$result-&gt;item(0)-&gt;deleteData(0, $result-&gt;item(0)-&gt;length);
print($dom-&gt;saveXML());
/*
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;library&gt;
    &lt;book&gt;
        &lt;title&gt;Eight apes ate eight apples&lt;/title&gt;
        &lt;author&gt;John&lt;/author&gt;
        &lt;publisher&gt;&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;9876543210&quot;&gt;
        &lt;title&gt;Strike&lt;/title&gt;
        &lt;author&gt;Mike&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;1234567890&quot;&gt;
        &lt;title&gt;Shine&lt;/title&gt;
        &lt;author&gt;Jack&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
&lt;/library&gt;
*/
?&gt;
</pre>
<div class="kakomi">
<h4>各メソッドについて</h4>
<dl>
<dt>DomNode <strong>DomNode::removeChild</strong>(DomNode $node)</dt>
<dd>DomNode内から、引数で指定したノードを削除する。</dd>
<dt>bool <strong>DomElement::removeAttribute</strong>(string $name)</dt>
<dd>DomNodeの、引数で指定した属性を削除する。</dd>
<dt>void <strong>DomCharacterData::deleteData</strong>(int $offset, int $count)</dt>
<dd>DomCharacterDataを対象として、第一引数で指定したオフセット値から、第二引数で指定した文字数分削除する。</dd>
</dl>
</div>
<h3>■DOMにおける名前空間の扱い方</h3>
<p>以下のように、要素や属性に名前空間を指定した記述をした後で、名前空間とそのURIを示す属性を要素に追加することで、名前空間を扱うことができる。</p>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$node = $dom-&gt;createElement('ns1:somenode');
$node-&gt;setAttribute('ns2:someattribute', 'somevalue');
$node2 = $dom-&gt;createElement('ns3:anothernode');
$node-&gt;appendChild($node2);

$node-&gt;setAttribute('xmlns:ns1', 'http://sample.org/ns1');
$node-&gt;setAttribute('xmlns:ns2', 'http://sample.org/ns2');
$node-&gt;setAttribute('xmlns:ns3', 'http://sample.org/ns3');

$dom-&gt;appendChild($node);
print($dom-&gt;saveXML());
/*
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;ns1:somenode ns2:someattribute=&quot;somevalue&quot; xmlns:ns1=&quot;http://sample.org/ns1&quot; xmlns:ns2=&quot;http://sample.org/ns2&quot; xmlns:ns3=&quot;http://sample.org/ns3&quot;&gt;
    &lt;ns3:anothernode/&gt;
&lt;/ns1:somenode&gt;
*/
?&gt;
</pre>
<p>但し、以下のようにDomNode::createElementNSメソッドや、DomNode::setAttributeNSを使用すると、自ノードと親ノードに名前空間とそのURIを示す属性が自動的に付加される。</p>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();

$node = $dom-&gt;createElementNS('http://sample.org/ns1', 'ns1:somenode');
$node-&gt;setAttributeNS('http://sample.org/ns2', 'ns2:someattribute', 'somevalue');

$node2 = $dom-&gt;createElementNS('http://sample.org/ns3', 'ns3:anothernode');
$node3 = $dom-&gt;createElementNS('http://sample.org/ns1', 'ns1:someothernode');

$node-&gt;appendChild($node2);
$node-&gt;appendChild($node3);

$dom-&gt;appendChild($node);

print($dom-&gt;saveXML());
/*
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;ns1:somenode xmlns:ns1=&quot;http://sample.org/ns1&quot; xmlns:ns2=&quot;http://sample.org/ns2&quot; xmlns:ns3=&quot;http://sample.org/ns3&quot; ns2:someattribute=&quot;somevalue&quot;&gt;
    &lt;ns3:anothernode xmlns:ns3=&quot;http://sample.org/ns3&quot;/&gt;
    &lt;ns1:someothernode/&gt;
&lt;/ns1:somenode&gt;
*/
?&gt;
</pre>
<p>出力されるXMLは若干違うものの、後者のコードの方が短くシンプルにはなる。</p>
<h3>■SimpleXMLとの相互変換</h3>
<h4>SimpleXMLからDOMへの変換</h4>
<p>以下のように、dom_import_simplexml関数を使用してSimpleXMLからDOMへ変換が行える。</p>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('test.xml', null, true);
$node = dom_import_simplexml($xml);

$dom = new DomDocument();
$dom-&gt;importNode($node, true);
$dom-&gt;appendChild($node);

print($dom-&gt;saveXML());
?&gt;
</pre>
<h4>DOMからSimpleXMLへの変換</h4>
<p>以下のように、simplexml_import_dom関数を使用してDOMからSimpleXMLへ変換が行える。</p>
<pre class="brush: php;">
&lt;?php
$dom = new DomDocument();
$dom-&gt;load('test.xml');
$xml = simplexml_import_dom($dom);
print($xml-&gt;asXML());
?&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.justoneplanet.info/2009/05/19/php-dom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP SimpleXML</title>
		<link>http://blog.justoneplanet.info/2009/05/16/php-simplexml/</link>
		<comments>http://blog.justoneplanet.info/2009/05/16/php-simplexml/#comments</comments>
		<pubDate>Fri, 15 May 2009 15:26:52 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://blog.justoneplanet.info/?p=1226</guid>
		<description><![CDATA[以下のXMLを使用してサンプルコードを解説する。 &#60;?xml version=&#34;1.0&#34;?&#62; &#60;library&#62; &#60;book isbn=&#34;0111222333&#038; [...]]]></description>
			<content:encoded><![CDATA[<p>以下のXMLを使用してサンプルコードを解説する。</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;library&gt;
    &lt;book isbn=&quot;0111222333&quot;&gt;
        &lt;title&gt;She sells seashells&lt;/title&gt;
        &lt;author&gt;Emily&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;0123456789&quot;&gt;
        &lt;title&gt;Eight apes ate eight apples&lt;/title&gt;
        &lt;author&gt;John&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;9876543210&quot;&gt;
        &lt;title&gt;Strike&lt;/title&gt;
        &lt;author&gt;Mike&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;1234567890&quot;&gt;
        &lt;title&gt;Shine&lt;/title&gt;
        &lt;author&gt;Jack&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
&lt;/library&gt;
</pre>
<h3>■XMLドキュメントのパース</h3>
<ul>
<li>対応しているXMLのバージョンは1.0（1.1は非対応）</li>
<li>パースに失敗すると警告を発する</li>
<li>ドキュメントをパースするときは、SimpleXMLElementオブジェクトを生成する必要がある</li>
</ul>
<pre class="brush: php;">
&lt;?php
$xml = simplexml_load_file('doc/library.xml');
?&gt;
</pre>
<p>上述のコードは以下のコードと同じ働きをする。</p>
<pre class="brush: php;">
&lt;?php
$doc = file_get_contents('doc/library.xml');
$xml = simplexml_load_string($doc);
?&gt;
</pre>
<h4>オブジェクト指向型のアプローチ</h4>
<p>以下のようにSimpleXMLElementクラスを使って、アブじぇ句と指向型のアプローチを取ることもできる。</p>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('doc/library.xml', null, true);
?&gt;
</pre>
<p>上述のコードは以下のコードと同じ働きをする。</p>
<pre class="brush: php;">
&lt;?php
$doc = file_get_contents('doc/library.xml');
$xml = new SimpleXMLElement($doc);
?&gt;
</pre>
<p>個人的にはオブジェクト指向型のアプローチの方がコードがスッキリして好きだ。</p>
<div class="kakomi">
<h5>SimpleXMLElement(string $dat[, int $options[, bool $flag_uri[, string $namespace[, bool $is_prefix]]]])</h5>
<dl>
<dt>$dat</dt>
<dd>XML文字列。URLで指定する場合は、第三引数を「true」にしなければならない</dd>
<dt>$options</dt>
<dd>libxmlに渡すパラメータ。用途にもよるが、「null」を渡して使用することが多い</dd>
<dt>$flag_uri</dt>
<dd>第一引数がURLの場合は、「true」をセットしなくてはならない</dd>
</dl>
</div>
<h3>■要素と属性へのアクセス</h3>
<p>各要素にアクセスするには「->」を使用し、属性にアクセスするためには配列リテラルを使用する。</p>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('doc/library.xml', null, true);
foreach($xml-&gt;book as $book){
    print($book['isbn'] . PHP_EOL);
    print($book-&gt;title . PHP_EOL);
    print($book-&gt;author . PHP_EOL);
    print($book-&gt;publisher . PHP_EOL);
}
/*
0111222333
She sells seashells
Emily
store
-----
0123456789
Eight apes ate eight apples
John
shop
-----
9876543210
Strike
Mike
shop
-----
1234567890
Shine
Jack
store
-----
*/
?&gt;
</pre>
<p>但し、上述のコードには「子要素や属性の名前を知っていなければならない」という欠点がある。従って、以下のコードのように、要素名や属性名を取得するメソッドを使う方が良い。</p>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('doc/library.xml', null, true);
foreach($xml-&gt;children() as $child){
    print($child-&gt;getName() . PHP_EOL);
    foreach($child-&gt;attributes() as $attr){
        print(&quot;\t&quot; . $attr-&gt;getName() . ': ' . $attr . PHP_EOL);
    }
    foreach($child-&gt;children() as $sub){
        print(&quot;\t&quot; . $sub-&gt;getName() . ': ' . $sub . PHP_EOL);
    }
    print('-----' . PHP_EOL);
}
/*
book
isbn: 0111222333
title: She sells seashells
author: Emily
publisher: store
-----
book
isbn: 0123456789
title: Eight apes ate eight apples
author: John
publisher: shop
-----
book
isbn: 9876543210
title: Strike
author: Mike
publisher: shop
-----
book
isbn: 1234567890
title: Shine
author: Jack
publisher: store
-----
*/
?&gt;
</pre>
<p>但し、上述のコードでは深さが特定の場合しか探索できない。深さが不定の場合は、再帰関数やRecursiveIteratorIteratorクラスなどを使用する。</p>
<h4>一度値を配列に格納する方法</h4>
<p>すぐに出力する場合は上述の方法で問題はないが、配列に要素の文字列を格納する場合はSimpleXMLElementオブジェクトから文字列に変換する。</p>
<pre class="brush: php;">
$data = new SimpleXMLElement($url, null, true);
if($data-&gt;getName() === 'rss'){//rss
    foreach($data-&gt;channel-&gt;item as $i){
        $rv[] = array(
            'title' =&gt; ((string)$i-&gt;title),
            'link'  =&gt; ((string)$i-&gt;link)
        );
    }
}
elseif($data-&gt;getName() === 'feed'){//atom
    foreach($data-&gt;entry as $item){
        $rv[] = array(
            'title' =&gt; ((string)$item-&gt;title),
            'link'  =&gt; ((string)$item-&gt;link['href'])
        );
    }
}
</pre>
<div class="kakomi">
<h5>各メソッドについて</h5>
<dl>
<dt>SimpleXMLElement::children()</dt>
<dd>指定したノードの子ノードを見つける</dd>
<dt>SimpleXMLElement::attributes()</dt>
<dd>属性名をキーとして、指定したノードの属性値の配列を返す</dd>
<dt>SimpleXMLElement::getName()</dt>
<dd>要素名、属性名を返す</dd>
</dl>
</div>
<h3>■XPathクエリ</h3>
<p>XPathを使用して特定の要素を抜き出したりするには、以下のように「SimpleXMLElement::xpath」を用いる。</p>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('doc/library.xml', null, true);
$elm = $xml-&gt;xpath('/library/book/title');
foreach($eml as $title){
    print($title . PHP_EOL);
}
/*
She sells seashells
Eight apes ate eight apples
Strike
Shine
*/
/*
array(4) {
  [0]=&gt;
  object(SimpleXMLElement)#2 (1) {
    [0]=&gt;
    string(19) &quot;She sells seashells&quot;
  }
  [1]=&gt;
  object(SimpleXMLElement)#3 (1) {
    [0]=&gt;
    string(27) &quot;Eight apes ate eight apples&quot;
  }
  [2]=&gt;
  object(SimpleXMLElement)#4 (1) {
    [0]=&gt;
    string(6) &quot;Strike&quot;
  }
  [3]=&gt;
  object(SimpleXMLElement)#5 (1) {
    [0]=&gt;
    string(5) &quot;Shine&quot;
  }
}
*/
?&gt;
</pre>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('doc/library.xml', null, true);
$elm = $xml-&gt;book[0]-&gt;xpath('title');
foreach($elm as $title){
    print($title . PHP_EOL);
}
//She sells seashells
?&gt;
</pre>
<div class="kakomi">
<h4>SimpleXMLElement::xpathメソッドのについて</h4>
<p>xpathクエリを実行し、結果をSimpleXMLElementオブジェクトとして返す。</p>
</div>
<h3>■SimpleXMLによるXMLドキュメントの操作</h3>
<p>以下のように、PHP5.1.3以降ではSimpleXMLで要素の追加が行えるようになった。</p>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('doc/library.xml', null, true);

$book = $xml-&gt;addChild('book');
$book-&gt;addAttribute('isbn', '0812550706');
$book-&gt;addChild('title', 'She sells seashells');
$book-&gt;addChild('author', 'John');
$book-&gt;addChild('publisher', 'amazon');

header('Content-type: text/xml');
print($xml-&gt;asXML());
/*
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;library&gt;
    &lt;book isbn=&quot;0111222333&quot;&gt;
        &lt;title&gt;She sells seashells&lt;/title&gt;
        &lt;author&gt;Emily&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;0123456789&quot;&gt;

        &lt;title&gt;Eight apes ate eight apples&lt;/title&gt;
        &lt;author&gt;John&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;9876543210&quot;&gt;
        &lt;title&gt;Strike&lt;/title&gt;
        &lt;author&gt;Mike&lt;/author&gt;

        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;1234567890&quot;&gt;
        &lt;title&gt;Shine&lt;/title&gt;
        &lt;author&gt;Jack&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;

&lt;book isbn=&quot;0812550706&quot;&gt;&lt;title&gt;She sells seashells&lt;/title&gt;&lt;author&gt;John&lt;/author&gt;&lt;publisher&gt;amazon&lt;/publisher&gt;&lt;/book&gt;&lt;/library&gt;
*/
?&gt;
</pre>
<p>asXMLメソッドは<strong>XML文字列を返す</strong>。また、引数にファイルパスを指定した場合は、XMLドキュメントとして保存される。但し、既にファイルが存在している場合は、警告なしにファイルが上書きされるので注意が必要である。</p>
<h4>要素の削除</h4>
<p>SimpleXMLは要素や属性の追加についてのメソッドを持っているが、<del datetime="2009-08-26T12:18:30+00:00">削除についてのメソッドは存在しない。削除する場合は以下のようにする。</del></p>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('doc/library.xml', null, true);
$xml-&gt;book[0] = null;
/*
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;library&gt;
    &lt;book isbn=&quot;0111222333&quot;&gt;&lt;/book&gt;
    &lt;book isbn=&quot;0123456789&quot;&gt;
        &lt;title&gt;Eight apes ate eight apples&lt;/title&gt;
        &lt;author&gt;John&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;

    &lt;book isbn=&quot;9876543210&quot;&gt;
        &lt;title&gt;Strike&lt;/title&gt;
        &lt;author&gt;Mike&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;1234567890&quot;&gt;
        &lt;title&gt;Shine&lt;/title&gt;

        &lt;author&gt;Jack&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
&lt;/library&gt;
*/
?&gt;
</pre>
<p>但し、この方法は要素内を空にするだけであり、book要素の属性も属性値を空にすることしかできない。もしも、完全に削除したい場合は、<del datetime="2009-08-26T12:18:30+00:00">DOMへエクスポートする必要がある。</del>以下のようにする。</p>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('doc/library.xml', null, true);
unset($xml-&gt;book[0]);
/*
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;library&gt;

    &lt;book isbn=&quot;0123456789&quot;&gt;
        &lt;title&gt;Eight apes ate eight apples&lt;/title&gt;
        &lt;author&gt;John&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;

    &lt;book isbn=&quot;9876543210&quot;&gt;

        &lt;title&gt;Strike&lt;/title&gt;
        &lt;author&gt;Mike&lt;/author&gt;
        &lt;publisher&gt;shop&lt;/publisher&gt;
    &lt;/book&gt;
    &lt;book isbn=&quot;1234567890&quot;&gt;
        &lt;title&gt;Shine&lt;/title&gt;

        &lt;author&gt;Jack&lt;/author&gt;
        &lt;publisher&gt;store&lt;/publisher&gt;
    &lt;/book&gt;
&lt;/library&gt;
*/
?&gt;
</pre>
<div class="kakomi">
<h5>各メソッドについて</h5>
<dl>
<dt>SimpleXMLElement::addChild</dt>
<dd>要素を追加する。戻り値はSimpleXMLElementオブジェクトであり、これに対して操作することでルートのXMLを操作することもできる</dd>
<dt>SimpleXMLElement::addAttribute</dt>
<dd>属性を追加する</dd>
</dl>
</div>
<h3>■名前空間</h3>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;library xmlns=&quot;http://sample.org/library&quot; xmlns:meta=&quot;http://sample.org/book-meta&quot; xmlns:pub=&quot;http://sample.org/publisher&quot; xmlns:sample=&quot;http://sample.org/sample&quot;&gt;
    &lt;book meta:isbn=&quot;0345342968&quot;&gt;
        &lt;title&gt;Fahrenheit 451&lt;/title&gt;
        &lt;author&gt;Ray Bradbury&lt;/author&gt;
        &lt;pub:publisher&gt;Del Rey&lt;/pub:publisher&gt;
    &lt;/book&gt;
&lt;/library&gt;
</pre>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('test.xml', null, true);
$ns = $xml-&gt;getDocNamespaces();
foreach($ns as $key =&gt; $value){
	print(&quot;{$key}: {$value}\n&quot;);
}
/*
: http://sample.org/library
meta: http://sample.org/book-meta
pub: http://sample.org/publisher
sample: http://sample.org/sample
*/
?&gt;
</pre>
</p>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('test.xml', null, true);
$ns = $xml-&gt;getNamespaces(true);
foreach($ns as $key =&gt; $value){
	print(&quot;{$key}: {$value}\n&quot;);
}
/*
: http://sample.org/library
meta: http://sample.org/book-meta
pub: http://sample.org/publisher
*/
?&gt;
</pre>
<p>以下のように、引数にfalseを指定するとカレントノードの名前空間を返す。名前空間が指定されていない場合は、空の配列となる。</p>
<pre class="brush: php;">
&lt;?php
$xml = new SimpleXMLElement('test.xml', null, true);
$ns = $xml-&gt;getNamespaces(false);
foreach($ns as $key =&gt; $value){
	print(&quot;{$key}: {$value}\n&quot;);
}
/*
: http://sample.org/library
*/
?&gt;
</pre>
<div class="kakomi">
<h4>各メソッドについて</h4>
<dl>
<dt></dt>
<dd></dd>
<dt>SimpleXMLElement::getDocNamespaces</dt>
<dd>ドキュメントで<strong>宣言されている</strong>名前空間を返す。引数にはbool値が入り（デフォルトはfalse）trueを指定すると、子ノードで宣言されている名前空間も返す。</dd>
<dt>SimpleXMLElement::getNamespaces</dt>
<dd>ドキュメントで<strong>使用している</strong>名前空間を返す。引数にはbool値が入り（デフォルトはfalse）trueを指定すると、子ノードで使用している名前空間も返す。</dd>
</dl>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.justoneplanet.info/2009/05/16/php-simplexml/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

