0

我正在使用 php 和 xpath 来显示一个 xml 文件,该文件具有这样的 xml 代码:

<?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>

和这样的php代码:

<?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>";
}
  }
?>

代码运行良好,打印结果如下:

Petrosino, ITALY
Traiskirchen, AUSTRIA

在这里,如果数据与字符串模式匹配,我不知道如何打印数据。就像我传递字符串“lon”一样,它只显示那些具有“lon”字符串模式的城市名称,例如“london”

请在这件事上给予我帮助

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 回答