2017-06-16 31 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>