【问题标题】:PHP to convert <img> tag to custom XMLPHP 将 <img> 标签转换为自定义 XML
【发布时间】:2017-01-29 08:55:04
【问题描述】:

我正在为一个小项目自学 PHP。我需要将源 HTML 文件(可能有很多)中的所有标签转换为自定义 XML。我一直在尝试使用 DOMDocument 类,但似乎无法正常工作。

例如,我需要转换

<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>

希望得到一些帮助...在此先感谢!

【问题讨论】:

  • 请展示你的尝试。

标签: php html xml


【解决方案1】:

使用以下代码获取 XML 字符串:

<?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;

结果:

<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>

如果这不是您想要的解决方案或有问题,请告诉我。

编辑:最佳解决方案是我创建的http://syframework.alwaysdata.net/44j。

【讨论】:

  • 嗨...非常感谢。这对我来说是一个好的开始,我修改了代码,以便它 1. 循环所有图像和 2. 用 XML 替换原始 标记。所有图像的循环都有效,但是由于某种原因,当我尝试用 XML 替换 标记时,我遇到了一些奇怪的问题。有任何想法吗?谢谢!代码有点长,这里放了,所以我把它放在这个链接syframework.alwaysdata.net/41r
  • 嗨。原谅我迟到了。转到http://syframework.alwaysdata.net/44j 以获得最佳解决方案。它比旧的更快更好。
  • 嗨!告诉我你的问题已经解决了。
【解决方案2】:
<image>
  <src>the url to the image</src>
  <alt>alt_Description_</alt>
  <description>Add_Image_description</description>
  <class>Image_Class_Add_</class>
  <height>Image_height_in_pixels</height>
  <width>Image_width_in_pixels</width>
  <title>Whatever_title_you_want_for_the_image</title>
</image>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多