通过php DOMDocument获取相同的标记值形式xml

时间:2022-11-27 17:10:16

I have a XML file, one part of the file is

我有一个XML文件,文件的一部分是

<Images>
     <image_>image1.jpg</image_>
     <image_>image2.jpg</image_>
</Images>

I need the image names. I use the code like

我需要图像名称。我使用的代码就像

$Images = $domtree->getElementsByTagName('Images');
foreach($Images as $Image){


    $Image = $Image->nodeValue."<br>";

    echo $Image;

    }

This is returns the imaged name but at a time as a string, I need as an array. I mean I want to insert the images in the database. Some one help me.

这将返回成像名称,但一次作为字符串,我需要作为一个数组。我的意思是我想在数据库中插入图像。谁来帮帮我。

1 个解决方案

#1


1  

The problem is you are looping over the Images element(s). So, when you echo nodeValue, you are getting the value of the entire Images element (and all its children).

问题是你正在循环Images元素。因此,当您回显nodeValue时,您将获得整个Images元素(及其所有子元素)的值。

You need to loop over each of the image_ elements (children) inside the Images element (parent)

你需要遍历Images元素(parent)中的每个image_元素(子元素)

$val = array();
$Images = $DOM->getElementsByTagName('Images');
foreach($Images as $Image){
    $imgs = $Image->getElementsByTagName('image_');
    foreach($imgs as $i){
        $img = $i->nodeValue;
        $val[] = $img;
        echo $img."<br>";
    }
}
var_dump($val);

#1


1  

The problem is you are looping over the Images element(s). So, when you echo nodeValue, you are getting the value of the entire Images element (and all its children).

问题是你正在循环Images元素。因此,当您回显nodeValue时,您将获得整个Images元素(及其所有子元素)的值。

You need to loop over each of the image_ elements (children) inside the Images element (parent)

你需要遍历Images元素(parent)中的每个image_元素(子元素)

$val = array();
$Images = $DOM->getElementsByTagName('Images');
foreach($Images as $Image){
    $imgs = $Image->getElementsByTagName('image_');
    foreach($imgs as $i){
        $img = $i->nodeValue;
        $val[] = $img;
        echo $img."<br>";
    }
}
var_dump($val);