tags:

views:

139

answers:

3

Hello all,

I am returned the following:

<links>
    <image_link>http://img357.imageshack.us/img357/9606/48444016.jpg&lt;/image_link&gt;
    <thumb_link>http://img357.imageshack.us/img357/9606/48444016.th.jpg&lt;/thumb_link&gt;
    <ad_link>http://img357.imageshack.us/my.php?image=48444016.jpg&lt;/ad_link&gt;
    <thumb_exists>yes</thumb_exists>
    <total_raters>0</total_raters>
    <ave_rating>0.0</ave_rating>
    <image_location>img357/9606/48444016.jpg</image_location>
    <thumb_location>img357/9606/48444016.th.jpg</thumb_location>
    <server>img357</server>
    <image_name>48444016.jpg</image_name>
    <done_page>http://img357.imageshack.us/content.php?page=done&amp;amp;l=img357/9606/48444016.jpg&lt;/done_page&gt;
    <resolution>800x600</resolution>
    <filesize>38477</filesize>
    <image_class>r</image_class>
</links>

I wish to extract the image_link in PHP as simply and as easily as possible. How can I do this?

Assume, I can not make use of any extra libs/plugins for PHP. :)

Thanks all

+1  A: 

use regular expressions

$text = 'string_input';
preg_match('/<image_link>([^<]+)</image_link>/gi', $text, $regs);
$result = $regs[0];
Josh
you need start and end delimiters for preg_match()
Tom Haigh
Great Idea! But I get Unknown modifier 'a' for some reason?
Abs
that's because you have an / in <image_link>. It thinks that is the end the regex, the 'i' in image is then a modifier, but it falls over when it gets to 'a' (not a valid modifier). Either escape any forward slashes within the delimiters or use a different delimiter not contained within the pattern (e.g. ~ or |)
Tom Haigh
Sorry, I meant you have a / in </image_link>
Tom Haigh
+2  A: 

You can use SimpleXML as it is built in PHP.

usoban
+3  A: 

At Josh's answer, the problem was not escaping the "/" character. So the code Josh submitted would become:

$text = 'string_input';
preg_match('/<image_link>([^<]+)<\/image_link>/gi', $text, $regs);
$result = $regs[0];

Taking usoban's answer, an example would be:

<?php

// Load the file into $content

$xml = new SimpleXMLElement($content) or die('Error creating a SimpleXML instance');

$imagelink = (string) $xml->image_link; // This is the image link

?>

I recommend using SimpleXML because it's very easy and, as usoban said, it's builtin, that means that it doesn't need external libraries in any way.

Pedro Cunha
SimpleXMLElement worked very well.
Abs