2017-06-16 14 views
1

很抱歉,如果标题不是很好。PHP用<g>标签与特定ID替换<circle>的每个填充颜色

我正在使用PHP编写一个脚本,它将改变<circle>的填充颜色,如果它位于具有特定ID的<g>之内。

这里是特定的字符串:

<g id="stroke"> 
<circle cx="6.628mm" cy="23.164mm" r="1.50mm" fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm"/> 
<circle cx="3.920mm" cy="20.170mm" r="1.50mm" fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm"/> 
</g> 
<g id="fill" style="visibility: hidden;"> 
<circle cx="22.593mm" cy="31.429mm" r="1.50mm" fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/> 
<circle cx="22.593mm" cy="27.381mm" r="1.50mm" fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/> 
</g> 

所以,我的想法是:

Change fill="#B8BBC0" to fill="#000000" IF inside <g id="stroke"> 
Change fill="#B8BBC0" to fill="#FFFFFF" IF inside <g id="fill"> 

我不能完全肯定的最好的方法来做到这一点。我知道replace()的基本知识,但我不知道如何编写代码以便用特定的id替换两个标签。任何人都可以帮我写这个吗?

+0

你想要我们做什么? –

+0

请参阅编辑 - 理想情况下,我需要编写脚本的帮助。 – Bren

+0

你有什么尝试? –

回答

0

下面是使用一个例子DOMDocument

$data = <<<DATA 
<?xml version="1.0"?> 
<root> 
<g id="stroke"> 
<circle cx="6.628mm" cy="23.164mm" r="1.50mm" fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm"/> 
<circle cx="3.920mm" cy="20.170mm" r="1.50mm" fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm"/> 
</g> 
<g id="fill" style="visibility: hidden;"> 
<circle cx="22.593mm" cy="31.429mm" r="1.50mm" fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/> 
<circle cx="22.593mm" cy="27.381mm" r="1.50mm" fill="#B8BBC0" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/> 
</g> 
</root> 
DATA; 

$dom = new DOMDocument; 
$dom->loadXML($data); 
$xpath = new DOMXPath($dom); 

$gstrokes = $xpath->query('//g[@id="stroke"]/circle[@fill]'); // Get CIRCLEs (with fill attribute) inside G with ID "stroke" 
foreach($gstrokes as $c) {     // Loop through all CIRCLEs found 
    $c->setAttribute('fill', '#000000');  // Set fill="#000000" 
} 
$gstrokes = $xpath->query('//g[@id="fill"]/circle[@fill]'); // Get CIRCLEs (with fill attribute) inside G with ID "fill" 
foreach($gstrokes as $c) {     // Loop through all CIRCLEs found 
    $c->setAttribute('fill', '#FFFFFF');  // Set fill="#000000" 
} 

echo $dom->saveXML();      // Save XML 

online PHP demo

结果:

<?xml version="1.0"?> 
<root> 
<g id="stroke"> 
<circle cx="6.628mm" cy="23.164mm" r="1.50mm" fill="#000000" stroke="#000000" stroke-width="0.282mm"/> 
<circle cx="3.920mm" cy="20.170mm" r="1.50mm" fill="#000000" stroke="#000000" stroke-width="0.282mm"/> 
</g> 
<g id="fill" style="visibility: hidden;"> 
<circle cx="22.593mm" cy="31.429mm" r="1.50mm" fill="#FFFFFF" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/> 
<circle cx="22.593mm" cy="27.381mm" r="1.50mm" fill="#FFFFFF" stroke="#000000" stroke-width="0.282mm" data-isfill="yes"/> 
</g> 
</root>