[英]Add attribute to child node XML using PHP
我正在努力在具有靜態唯一ID的XML文件中追加子節點。
我正在使用的XML提要托管在其他地方的服務器上,只能通過其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中的URL為“property”節點添加一個唯一的id,並在備用URL處輸出XML feed。
例如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>
有點像這樣:
<?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();
<?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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.