gpt4 book ai didi

PHP 的 SimpleXML : How to use colons in names

转载 作者:IT王子 更新时间:2023-10-29 00:11:38 24 4
gpt4 key购买 nike

我正在尝试使用 SimpleXML 生成 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 提要的每一行上,而不是在根元素中只有一次。

我错过了什么吗?

最佳答案

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

我认为您可能需要阅读 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', 'new', $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 : How to use colons in names,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3018808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com