我有一个看起来像这样的xml:
<host host-name="www.1.com">
<root-directory>c:/public_html</root-directory>
</host>
<host host-name="www.2.com">
<root-directory>c:/public_html</root-directory>
</host>
我需要像这样使用php修改xml
如果host-name的值= www.2.com
更改c:/ public_html / blahblah
中root目录的值所以最终的结果是:
<host host-name="www.1.com">
<root-directory>c:/public_html</root-directory>
</host>
<host host-name="www.2.com">
<root-directory>c:/public_html/blahblah</root-directory>
</host>
我真的需要一些帮助。谢谢!
更新
哦,我忘了提到我不是程序员,无论如何这里是我试过的$xmlDomain= "www.2.com";
$nomefile='myfile.xml';
$xmlDoc = new DomDocument();
$xmlDoc->load($nomefile);
$Xroot = $xmlDoc->documentElement;
$products = $Xroot->getElementsByTagName("host");
$length = $products->length;
for ($i=$length-1;$i>=0;$i--)
{
$p = $products->item($i);
$pid = $p->getAttribute("host-name");
if ($pid == $xmlDomain)
{
$parent = $xmlDoc->getElementsByTagName("root-directory");
$parent->nodeValue = 'c:/public_html/blahblah';
}
}
$strxml = $xmlDoc->saveXML();
$handle = fopen($nomefile, "w");
fwrite($handle, $strxml);
fclose($handle);
答案 0 :(得分:0)
好的,我需要离开编写文档一分钟,所以这里是:
function modifyRootDirectoryFormHosts(DOMDocument $doc, $hostNameToLookFor, $newRootDirectory)
{
$xpath = new DOMXPath($doc);
$items = $xpath->query(sprintf('//host[@host-name="%s"]', $hostNameToLookFor));
if (count($items) > 0)
{
foreach($items as $item)
{
foreach($item->getElementsByTagName('root-directory') as $rootDirElement)
{
$rootDirElement->removeChild($rootDirElement->firstChild);
$rootDirElement->appendChild($doc->createTextNode($newRootDirectory));
}
}
}
}
$xmlSource = <<<XML
<root>
<host host-name="www.1.com">
<root-directory>c:/public_html</root-directory>
</host>
<host host-name="www.2.com">
<root-directory>c:/public_html</root-directory>
</host>
</root>
XML;
$doc = new DOMDocument();
$doc->loadXML($xmlSource);
modifyRootDirectoryFormHosts($doc, 'www.2.com', 'c:/public_html/blahblah');
echo $doc->saveXML();
输出是:
<?xml version="1.0"?>
<root>
<host host-name="www.1.com">
<root-directory>c:/public_html</root-directory>
</host>
<host host-name="www.2.com">
<root-directory>c:/public_html/blahblah</root-directory>
</host>
</root>