我正在使用 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”
请在这件事上给予我帮助