2017-04-23 1 views
1

私が初めてのSimpleXMLElementと協力し、次のように私のXMLの行を生成する必要がありますよ:私は前に名前空間をaddAttributeを使用していないとできませんしているPHPのSimpleXMLElement addAttributeは、名前空間の構文

<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

をここで働く正しい構文を取得する - 私はこれを始めました:

$node = new SimpleXMLElement('<Product></Product >'); 
$node->addAttribute("xmlns:", "xsd:", 'http://www.w3.org/2001/XMLSchema-instance'); 

をが、所望の出力を生成するために、適切な構文については、これを修正する方法を考え出すことはできませんか?

答えて

0

解決策1:接頭辞にプレフィックスを追加

<?php 
$node = new SimpleXMLElement('<Product/>'); 
$node->addAttribute("xmlns:xmlns:xsi", 'http://www.w3.org/2001/XMLSchema-instance'); 
$node->addAttribute("xmlns:xmlns:xsd", 'http://www.w3.org/2001/XMLSchema'); 
echo $node->asXML(); 

出力:

<?xml version="1.0"?> 
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/> 

注:この回避策で、実際に属性の名前空間を設定しませんが、エコー/保存して結果をファイルに保存する場合は、ちょうど十分です。

ソリューション2:名前空間を直接入力SimpleXMLElementコンストラクタ

<?php 
$node = new SimpleXMLElement('<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>'); 
echo $node->asXML(); 

出力LYは、溶液3 1

溶液と同じである(追加の属性を追加)

<?php 
$node = new SimpleXMLElement('<Product/>'); 
$node->addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance", "xmlns"); 
$node->addAttribute("xmlns:xsd", 'http://www.w3.org/2001/XMLSchema', "xmlns"); 
echo $node->asXML(); 

出力は、さらなる加算xmlns:xmlns="xmlns"

<?xml version="1.0"?> 
<Product xmlns:xmlns="xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/> 
関連する問題