XMl
如下所示,
<text font-family="Helvetica" font-size="25" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;" >
<tspan x="-100" y="7.87" style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: ; opacity: 1;">t</tspan>
<tspan x="-93" y="7.87" style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: ; opacity: 1;">e</tspan>
<tspan x="-79" y="7.87" style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: ; opacity: 1;">s</tspan>
<tspan x="-66" y="7.87" style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: ; opacity: 1;">t</tspan>
</text>
我想要做的是,先保留tspan
并在第一个tspan
上附加所有其他tspan
值,然后删除所有其他值。
他是理想的输出,
<text font-family="Helvetica" font-size="25" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;" >
<tspan x="-100" y="7.87" style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: ; opacity: 1;">test</tspan>
</text>
对于我所做的,
$previousValue = null;
$first = $text->tspan[0];
foreach($text->tspan as $k2=>$span){
if(is_object($span)){
$style = $span->attributes()->style;
if($previousValue) {
if(strcmp($style,$previousValue) === 0){
$first.=$span;
//$dom=dom_import_simplexml($span); $dom->parentNode->removeChild($dom);
}
}
$previousValue = $style;
}
}
$text->tspan[0] = $first;
这将生成第一个节点完美,但不能正确删除其他节点。 我甚至尝试过这个,
$dom=dom_import_simplexml($span); $dom->parentNode->removeChild($dom);
但它只是删除1个节点然后打破循环。不知道那里发生了什么。我在那里犯了什么错吗?
答案 0 :(得分:1)
使用SimpleXMLElement和XPath,您可以执行以下操作:
$xml = new SimpleXMLElement($xmlString);
$texts = $xml->xpath('//text/tspan/..');
foreach ($texts as $text) {
$tspans = $text->xpath('//tspan');;
$currentTspan = array_shift($tspans);
foreach ($tspans as $tspan) {
if ($currentTspan['style']->asXML() != $tspan['style']->asXML()) {
$currentTspan = $tspan;
continue;
}
$currentTspan[0] .= $tspan[0];
unset($tspan[0]);
}
}
为了简单起见,我在这里使用了array_shift()函数。它只是返回数组的第一个元素并将其删除。