cybernaut
cybernaut

Reputation: 21

How to add 'id' attribute to elements in XML based upon other element values

Would very much appreciate help on how to achieve the outcome below - being able to add the id attribute to the <image> tags with a PHP snippet or any methods.

<?xml version="1.0" encoding="utf-8"?>
<root>
    <property>
        <images>
            <image id="1">
                <url>http://www.mywebsite/image?id=1&.jpg</url>
            </image>
            <image id="2">
                <url>http://www.mywebsite/image?id=2&.jpg</url>
            </image>
        </images>
    </property>
</root> 

Upvotes: 1

Views: 2622

Answers (2)

Baba
Baba

Reputation: 95101

I guess you want to create xml same has above

$array = array(
        "http://www.mywebsite/image?id=1&.jpg",
        "http://www.mywebsite/image?id=2&.jpg"
);

header('Content-Type:text/plain');
$xml = new SimpleXMLElement("<root></root>");
$property = $xml->addChild('property');
$images = $property->addChild('images');

foreach($array as $link) {
    parse_str(parse_url($link, PHP_URL_QUERY), $query);

    $image = $images->addChild('image');
    $image->addAttribute("id", $query['id']);
    $url = $image->addChild("url", urlencode($link));
}

echo $xml->asXML();

Upvotes: 1

nickhar
nickhar

Reputation: 20833

If you're reading in a string, then you can loop over <images> and add the id attribute to each <image>.

Note: Your XML is throwing errors due to the & in your urls, so I've substituted them with &amp; for the sake of a working example.

header('Content-Type:text/plain');
$xmlstring = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
    <property>
        <images>
            <image>
                <url>http://www.mywebsite/image?id=1&amp;.jpg</url>
            </image>
            <image>
                <url>http://www.mywebsite/image?id=2&amp;.jpg</url>
            </image>
        </images>
    </property>
</root>
XML;

$xml = simplexml_load_string($xmlstring);

foreach ($xml->property->images->image as $image)
{
    parse_str(parse_url($image->url, PHP_URL_QUERY), $querystring);
    $image->addAttribute("id", $querystring['id']);
}

echo $xml->asXML();

This same method could also be achieved by reading in an XML file instead of a string:

$xml = simplexml_load_file('path/to/file.xml');

Upvotes: 0

Related Questions