我很难在具有静态唯一ID的XML文件中附加子节点。
我正在使用的XML Feed托管在其他地方的服务器上,只能通过其URL访问。
所述饲料遵循以下这种模式:
<?xml version="1.0" encoding="UTF-8"?>
<properties>
<property>
<title>Some Sunny Place</title>
<address>Some Building, Somewhere, Really Nice</address>
</property>
<property>
<title>Some Rainy PLace Place</title>
<address>Some Gutter, Somewhere, Not So Nice</address>
</property>
</properties>
我想要实现的目标是使用Feed中的网址为“&#39;属性添加唯一ID”。节点并在备用URL处输出XML提要。
e.g。 example.com/proeprty-feed包含没有ID的feed。使用PHP添加ID并将feed输出到something.com/property-feed
<?xml version="1.0" encoding="UTF-8"?>
<properties>
<property upid=123456>
<title>Some Sunny Place</title>
<address>Some Building, Somewhere, Really Nice</address>
</property>
<property upid=abcdef>
<title>Some Rainy PLace Place</title>
<address>Some Gutter, Somewhere, Not So Nice</address>
</property>
</properties>
我试过的是input.php
<?php
$xmlstr = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<properties>
<property>
<title>Some Sunny Place</title>
<address>Some Building, Somewhere, Really Nice</address>
</property>
<property>
<title>Some Rainy PLace Place</title>
<address>Some Gutter, Somewhere, Not So Nice</address>
</property>
</properties>
XML;
?>
和output.php
<?php
include 'input.php';
$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('upid', uniqid('prop-'));
echo $sxe->asXML();
?>
但是这会输出:
<properties upid="prop-5ac7c06a39ddd">
<property>
<title>Some Sunny Place</title>
<address>Some Building, Somewhere, Really Nice</address>
</property>
<property>
<title>Some Rainy PLace Place</title>
<address>Some Gutter, Somewhere, Not So Nice</address>
</property>
</properties>
答案 0 :(得分:2)
有些事情如下:
<?php
$string = '<?xml version="1.0" encoding="UTF-8"?>
<properties>
<property>
<title>Some Sunny Place</title>
<address>Some Building, Somewhere, Really Nice</address>
</property>
<property>
<title>Some Rainy PLace Place</title>
<address>Some Gutter, Somewhere, Not So Nice</address>
</property>
</properties>';
$xml = new SimpleXMLElement($string);
for($i = 0; $i < count($xml -> property); $i++) {
$xml -> property[$i] -> addAttribute('upid', uniqid());
}
header('Content-Type: text/xml');
print $xml -> asXml();
答案 1 :(得分:0)
<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<properties>
<property>
<title>Some Sunny Place</title>
<address>Some Building, Somewhere, Really Nice</address>
</property>
<property>
<title>Some Rainy PLace Place</title>
<address>Some Gutter, Somewhere, Not So Nice</address>
</property>
</properties>';
$length = strlen('<property>');
while ($pos = strpos($xml, '<property>')) {
$xml = substr_replace($xml, '<property upid=' . uniqid() . '>', $pos, $length);
usleep(10); // Necessary so uniqid() is unique every iteration, it's kind of a hack not sure if it's the best solution
}
var_dump($xml);