简体   繁体   中英

Import data from xml

I'm trying to get data from an XML file using simple_xml , so far I can get all the data except the images . How can I call a single image name ?

<?php

$ur="http://services2.jupix.co.uk/api/get_properties.php?clientID=35871cc1b6d9ec6237aaaf94aa0e0836&passphrase=cvYG9f";
$xml = simplexml_load_file($ur);

foreach ($xml->property as $property):

var_dump($property->images->image);

echo 'images->image">'; // this is not displaying

 endforeach;?>

My code output as the image below . How can i display image number 1 public 1 => string ' http://media2.jupix.co.uk/v3/clients/657/properties/1356/IMG_1356_9_large.jpg ' (length=77)

在此输入图像描述

I think SimpleXMLElement::xpath can do what you are looking for:

You can give this a try:

<?php
$ur="http://services2.jupix.co.uk/api/get_properties.php?clientID=35871cc1b6d9ec6237aaaf94aa0e0836&passphrase=cvYG9f";
$xml = simplexml_load_file($ur);
$image = $xml->xpath('//property/images/image[@modified="2014-07-23 14:22:05"]')[1]->__toString();
var_dump($image);

Or you can loop through all the images and check for the name the you are looking for:

$images = $xml->xpath('//property/images/image');

foreach ($images as $image) {
    $url = $image->__toString();
    if (false !== strpos($url, "_9_large.jpg")) {
        var_dump($url);
    }
}

If you want to get the second image of each /images section, then you could do it like this:

$images = $xml->xpath('//property/images');
foreach ($images as $image) {
    if (isset($image->children()[1])) {
        var_dump($image->children()[1]->__toString());
    }
}

Thanks Guy I found solution to my problem . Looking at the back at the question it seems I did not put it in a proper way All i wanted is to display images within that section. Xpath was not necessary But i have learned from it . Here is my solution if you can improve it you are much welcome.

   $url ="http://services2.jupix.co.uk/api/get_properties.php?clientID=35871cc1b6d9ec6237aaaf94aa0e0836&passphrase=cvYG9f";
$xml = simplexml_load_file($url);
foreach ($xml->property as $property):
?>
    <li>
    <h3> <?php echo $property->addressStreet;?> </h3>

        <?php 
$imgCount = count($property->images->image);
    for ($i=0; $i < $imgCount; $i++) { ?>    

 <img src="<?php echo $property->images->image[$i];?>">     

        <?php } ?>
        <p><?php echo  limit_text($property->fullDescription,30);?></p>
          <h4>&pound; <?php echo $property->price;?> </h4>
    </li>
        <?php  endforeach; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM