PHP的SimpleXML:如何在名字中使用冒号

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP的SimpleXML:如何在名字中使用冒号脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Simple XML生成RSS GOOGLE Merchant.

Google提供的示例是:

<?XMl version="1.0"?>
<RSS version="2.0" 
xMLns:g="http://base.google.COM/ns/1.0">
<channel>
<tITle>The name of your data Feed</title>
<link>http://www.example.com</link>
<description>A description of your content</description>
<item>
<title>red wool sweater</title>
<link> http://www.example.com/item1-info-page.html</link>
<description>Comfortable and soft,this sweater will keep you warm on those cold winter nights.</description>
<g:image_link>http://www.example.com/image1.jpg</g:image_link> <g:PRice>25</g:price> <g:condition>new</g:condition> <g:id>1a</g:id>
</item>
</channel>
</RSS>

我的代码有:

$product->addChild("g:condition",'new');

哪个产生:

<condition>new</condition>

我在线阅读我应该改用:

$product->addChild("g:condition",'new','http://base.google.com/ns/1.0');

现在生成

<g:condition xmlns:g="http://base.google.com/ns/1.0">new</g:condition>

这似乎对我来说是非常反直觉的,因为现在的“xmlns”声明几乎是我的RSS Feed中几乎每一行在根元素中的一次.

我错过了什么吗?

@ceejayoz表示,您需要将“http://base.google.com/ns/1.0”命名空间添加到根节点,以便SimpleXML知道命名空间已经被声明,并且不会发出重复的前缀绑定.

我想你可能需要阅读tutorial on XML Namespaces,因为我不确定你真的明白“g:”在这里做什么.

这是一个更完整的例子.
XML:

$xml = <<<EOT 
<?xml version="1.0"?> 
<RSS version="2.0" xmlns:g="http://base.google.com/ns/1.0"> 
  <channel> 
    <title>The name of your data Feed</title> 
    <link>http://www.example.com</link> 
    <description>A description of your content</description> 
    <item> 
      <title>Red wool sweater</title> 
      <link> http://www.example.com/item1-info-page.html</link> 
      <description>Comfortable and soft,this sweater will keep you warm on those cold winter nights.</description> 
      <g:image_link>http://www.example.com/image1.jpg</g:image_link> 
      <g:price>25</g:price> 
      <g:id>1a</g:id> 
    </item> 
  </channel> 
</RSS> 
EOT 
;

码:

$RSS = new SimpleXMLElement($xml); 
$NS = array( 
    'g' => 'http://base.google.com/ns/1.0' 
); 
$RSS->registerxpathnamespace('g',$NS['g']); 
$product = $RSS->channel->item[0]; // example 

// Use the complete namespace. 
// Don't add "g" prefix to element name--what prefix will be used is 
// something SimpleXML takes care of. 
$product->addChild('condition',$NS['g']); 

echo $RSS->asXML();

我通常使用这种模式轻松处理命名空间:

$RSS = new SimpleXMLElement($xml); 
$NS = array( 
    'g' => 'http://base.google.com/ns/1.0' 
    // whatever other namespaces you want 
); 
// Now register them all in the root 
foreach ($NS as $prefix => $name) { 
    $RSS->registerXPathNamespace($prefix,$name); 
} 
// Then turn $NS to an object for more convenient Syntax 
$NS = (object) $NS; 
// If I need the namespace name later,I access like so: 
$element->addChild('localName','Value',$NS->g);

脚本宝典总结

以上是脚本宝典为你收集整理的PHP的SimpleXML:如何在名字中使用冒号全部内容,希望文章能够帮你解决PHP的SimpleXML:如何在名字中使用冒号所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。