簡體   English   中英

如何從 php 中的 xml 文件中刪除 html 屬性?

[英]How can I remove html attributes from xml file in php?

我有一個包含 HTML 的 XML 文件。 在 HTML 標簽中,有一些我想刪除的屬性,但我需要保留所有標簽。 一個例子是:

<description><![CDATA[<div><span style='font-size: 40px'>Testing123</span></div>]]></description>

我想刪除 'style' 屬性,以便輸出:

 <description><![CDATA[<div><span>Testing123</span></div>]]></description>

我可以使用preg_replace使這個工作正常工作,但是當我去保存文件時,格式已經偏離了。 換句話說,我想在解析/剝離我的文件后保留 XML 文件的格式。

編輯:我提供的初始示例數據不包括我的 XML 文件中的 CDATA。 我修改了那個。

我不確定格式,但嘗試使用 simplexml 和 unset() 函數:

$string = "<div><span style='font-size: 40px'>Testing123</span></div>";                                                                       
$xml = simplexml_load_string($string);
$target = $xml->xpath("//span/@style");
foreach ($target as $node) {
    unset($node[0]);
}

echo $xml->asXML();

輸出:

<?xml version="1.0"?>
<div><span>Testing123</span></div>

XSLT 3.0 解決方案:

<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="3.0"/>
 <mode on-no-match="shallow-copy"/>
 <template match="span/@style"/>
</transform>

您可以擴展匹配模式,或添加其他模板規則,具體取決於要刪除的屬性。

當然,XSLT 1.0 也是可能的,只是稍微冗長了一點。

您必須將 cdata 元素中的字符串加載為 XML(更正確的是: HTML ),然后刪除所有屬性,例如使用 xpath:

$xml = simplexml_load_string($buffer);
$cdata = simplexml_load_string((string)$xml);
foreach ($cdata->xpath('@*[name(.) != "id"]|*/@*') as $attribute) {
    unset($attribute[0]);
}

(比較:在 SimpleXML for PHP 中移除具有特定屬性的孩子的答案

然后,如果您需要保留 CDATA 元素,則必須執行 DOM 往返,因為 SimpleXML 沒有 CDATA 部分,但 DOMDocument 具有:

    if ($n = dom_import_simplexml($el)) {
        $cd = $n->ownerDocument->createCDATASection($data);
        $n->appendChild($cd);
    }

(比較:如何使用 SimpleXmlElement 編寫 CDATA?;查看 PHP 手冊了解更多詳細信息)

您還需要從$cdata創建 XML,但您希望刪除第一行,因為它包含XML 聲明

    rtrim(explode("\n", $el->asXML(), 2)[1]);

(比較: SimpleXML Type Cheatsheet 中的SimpleXML Line Separator

給定一個輸入,如:

$buffer=<<<XML
<description><![CDATA[<div id="2" style="all: inherit;"><span style='font-size: 40px'>Testing123</span></div>]]></description>
XML;

結果是:

<?xml version="1.0"?>
<description><![CDATA[<div id="2"><span>Testing123</span></div>]]></description>

3v4l.org 上的示例 7.3.0 - 7.3.29、7.4.0 - 7.4.21、8.0.0 - 8.0.8 的輸出:

<?xml version="1.0"?>
<description><![CDATA[<div id="2"><span>Testing123</span></div>]]></description>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM