0

I am using php and xpath to display an xml file which is having a xml code like this:

<?xml version="1.0" encoding="utf-8"?>
<cities>
  <city>
    <city_id>8393</city_id>
    <country>ITALY</country>
    <name>Petrosino</name>
    <establishment_count>1</establishment_count>
  </city>
  <city>
    <city_id>7920</city_id>
    <country>AUSTRIA</country>
    <name>Traiskirchen</name>
    <establishment_count>1</establishment_count>
  </city>
</cities>

and the php code like this:

<?php

$source = file_get_contents('cities.xml');
$xml = new SimpleXMLElement($source);

foreach ($xml as $node)
  {
    $row = simplexml_load_string($node->asXML());
    $result = $row->xpath("//city/name");
    if ($result[0])
    {

   $name = $row->name;
   echo "<div>".$name.", ".$row->country."</div>";
}
  }
?>

the code is doing fine and printing the result like this:

Petrosino, ITALY
Traiskirchen, AUSTRIA

here i dont know how to print the data if its matching the string pattern. Just like if i pass the string "lon" so its display only those city name which are having "lon" string pattern like "london"

please help me with this

4

2 に答える 2

0

preg_match を使用したい。例えば

$pattern = '/^lon/';
if (preg_match($pattern, $name)){
    // do your print out
}

詳細はこちら: http://php.net/manual/en/function.preg-match.php

于 2012-09-18T12:12:12.863 に答える
0

使用contains():

$string = '<?xml version="1.0" encoding="utf-8"?>
<cities>
  <city>
    <city_id>8393</city_id>
    <country>ITALY</country>
    <name>Petrosino</name>
    <establishment_count>1</establishment_count>
  </city>
  <city>
    <city_id>7920</city_id>
    <country>AUSTRIA</country>
    <name>Traiskirchen</name>
    <establishment_count>1</establishment_count>
  </city>
</cities>';

$xml = new SimpleXMLElement($string);
$result = $xml->xpath("//city/name[contains(., 'Pet')]");

print_r($result);

/*Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => Petrosino
        )

)*/

またはあなたの問題のために:

$string = 'Pet';
foreach ($xml as $node){
    $row = simplexml_load_string($node->asXML());
    $result = $row->xpath("name[contains(., '".$string."')]");
    if ($result[0]){
        $name = $row->name;
        echo "<div>".$name.", ".$row->country."</div>";
    }
}

コードパッドの例

大文字と小文字を区別しないため、やや醜いです:

$string = 'pet';
$result = $xml->xpath("//city[contains(translate(name,'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'), '".strtoupper($string)."')]");
foreach($result as $one){
    echo "<div>".$one->name.", ".$one->country."</div>";
}
于 2012-09-18T12:15:36.463 に答える