PHP转换< img>标记到自定义XML [英] PHP to convert <img> tag to custom XML
问题描述
我正在自学PHP来开发一个小项目。我需要将源HTML文件中的所有标记(可能有很多)转换为自定义XML。我一直在尝试DOMDocument类的东西,但似乎无法让东西正常工作。
I'm teaching myself PHP for a small project. I need to convert all of the tags in a source HTML file (there may be many) into custom XML. I've been trying out things with the DOMDocument class, but can't seem to get stuff to work right.
举例来说,我需要将
As an example, I need to convert
<img class="alignnone size-large wp-image-23904" src="https://picnic.ly/wp-content/uploads/2017/01/Screen-Shot-2560-01-27-at-2.32.06-PM-1024x572.png" alt="this is a picture" width="1024" height="574" />
至
<image>
<description>VALUE FROM ALT</description>
<url>VALUE FROM SRC</url>
</image>
想在这里提供一些帮助...提前致谢!
Would love some help on this ... thanks in advance!
推荐答案
使用下面的代码获取XML字符串:
Use below code to get XML string:
<?php
// We use dom document to load it as an php object
$document = new DOMDocument();
$document->loadHTML('<img class="alignnone size-large wp-image-23904" src="https://picnic.ly/wp-content/uploads/2017/01/Screen-Shot-2560-01-27-at-2.32.06-PM-1024x572.png" alt="this is a picture" width="1024" height="574" />');
$img = $document->getElementsByTagName("img")->item(0);
// The Wrapper for your xml
$xml = "<image>\n";
for ($i = 0; $i < $img->attributes->length; $i++) {
$attribute = $img->attributes->item($i);
$name = $attribute->name;
$value = $attribute->textContent;
// Indent the element
$xml .= " ";
// Create the element
$xml .= "<" . $name . ">";
$xml .= $value;
$xml .= "</" . $name . ">";
// Break line at end
$xml .= "\n";
}
$xml .= "</image>";
echo $xml;
以及结果:
and the result:
<image>
<class>alignnone size-large wp-image-23904</class>
<src>https://picnic.ly/wp-content/uploads/2017/01/Screen-Shot-2560-01-27-at-2.32.06-PM-1024x572.png</src>
<alt>this is a picture</alt>
<width>1024</width>
<height>574</height>
</image>
告诉我这是不是您想要的解决方案或存在问题。
Tell me if this is not your want solution or has problem.
编辑:最佳解决方案是 http://syframework.alwaysdata .net / 44j 我已创建。
EDIT: Best Solution is http://syframework.alwaysdata.net/44j i have created.
这篇关于PHP转换< img>标记到自定义XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!