简体   繁体   English

xml_parser属性提取

[英]xml_parser extraction of attributes

I wonder whether it is possible to convert this XML 我想知道是否可以转换此XML

<url name="profile_link">http://example.com/profile/2345/</url>

into this HTML 进入这个HTML

<a href="http://example.com/profile/2345/">http://example.com/profile/2345/</a>

with the PHP XML Parser . PHP XML Parser一起使用

I do not understand how to fill the href in my link. 我不明白如何在链接中填写href。 The URL (ie the data content) is accessible via the xml_set_character_data_handler(), but the start handler (exchanging the url with the anchor) was already called before that event is triggered. 可通过xml_set_character_data_handler()访问URL(即数据内容),但是在触发该事件之前已经调用了启动处理程序(与定位符交换url)。

Here are two approaches for this: 这是两种方法:

Replace the nodes using DOM 使用DOM替换节点

Replacing nodes requires less bootstrap. 更换节点所需的引导程序更少。 It is done completely in PHP. 它完全用PHP完成。

$xml = <<<'XML'
<url name="profile_link">http://example.com/profile/2345/</url>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

$nodes = $xpath->evaluate('//url');
foreach ($nodes as $node) {
  $link = $dom->createElement('a');
  $link->appendChild($dom->createTextNode($node->textContent));
  $link->setAttribute('href', $node->textContent);
  $node->parentNode->insertBefore($link, $node);
  $node->parentNode->removeChild($node);
}

var_dump($dom->saveXml($dom->documentElement));

Transform the XML using XSLT 使用XSLT转换XML

The second approach requires an XSLT template file. 第二种方法需要XSLT模板文件。 XSLT is an language designed to transform XML. XSLT是一种旨在转换XML的语言。 So the initial bootstrap is larger, but the actual transformation is easier to define. 因此,初始引导程序较大,但实际转换更容易定义。 I would suggest this approach if you need to do other transformations, too. 如果您还需要进行其他转换,我建议使用这种方法。

$xml = <<<'XML'
<url name="profile_link">http://example.com/profile/2345/</url>
XML;

$xsl = <<<'XSL'
<?xml version="1.0"?>
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="url">
  <a href="text()">
    <xsl:value-of select="text()"/>
  </a>
</xsl:template>

<!-- pass through for unknown tags in the xml tree -->
<xsl:template match="*">
  <xsl:element name="{local-name()}">
    <xsl:copy-of select="@*"/>
    <xsl:apply-templates select="node()"/>
  </xsl:element>
</xsl:template>

</xsl:stylesheet>
XSL;

$dom = new DOMDocument(); 
$dom->loadXml($xml); 

$xslDom =  new DOMDocument();
$xslDom->loadXml($xsl);

$xsltProc = new XsltProcessor();
$xsltProc->importStylesheet($xslDom);

$result = $xsltProc->transformToDoc($dom);

var_dump($result->saveXml($result->documentElement));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM