Lukesoft Lukesoft - 1 year ago 56
PHP Question

Parse XML with tags not grouped under one tag, but really should be

I happen to be unfortunate enough to be working with an api that has images on the same XML tag level as the other tags and have the subscripts i.e 1,2,3,4 as part of the tag name of the image. Total images of each vehicle will vary in count.

<TITLE>Some car name i dont need</TITLE>
<DESCRIPTION>Some description i also dont need</DESCRIPTION>
<IMAGE_URL1>{imagelinkhere i want}</IMAGE_URL1>
<IMAGE_URL2>{imagelinkhere i want}</IMAGE_URL2>
<IMAGE_URL3>{imagelinkhere i want}</IMAGE_URL3>
<IMAGE_URL4>{imagelinkhere i want}</IMAGE_URL4>

I am using PHP's method simplexml_load_file(xml_url) to parse the entire xml into an object array.

My question: Is there a way to get these images using the same method which is also efficient and clean?

I have just refined the xml to show that there are other tags i dont need there and already handling.

Answer Source
$xml = '<Vehicle>

$parsed = simplexml_load_string($xml);

If you know, that the image url tags will always contain the name IMAGE_URL, you can check them:

foreach ($parsed as $key => $image) {
    if (strpos($key, 'IMAGE_URL') !== false) {
        echo $image, '</br>';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download