3

我有一个看起来像这样的 XML 文件

<table id="0">
</table>
<table id="1">
</table>
<table id="2">
</table>

我想检查一个 id x 的表是否存在

我一直在尝试这个,但没有用。

$file=fopen("config.xml","a+");
while (!feof($file))
  {
      if(fgets($file). "<br>" === '<table id="0">'){
        echo fgets($file). "<br>";
      }
  }
fclose($file);
4

3 回答 3

4

最简单的方法是使用PHP Simple HTML DOM类:

$html = file_get_html('file.xml');
$ret = $html->find('div[id=foo]'); 

[编辑] 至于不起作用的代码...请注意,您粘贴的 xml 没有
字符,因此此字符串比较将返回 false。如果您想考虑换行,您应该编写\n...但是上面的解决方案更好,因为您不必获得格式非常严格的输入文件。

于 2013-10-22T17:41:57.420 回答
2

您可以使用DOMDocument 类,用 XPath 通过 ID 查找,有一个getElementById()方法,但它有问题。

// Setup sample data

$html =<<<EOT
<table id="0">
</table>
<table id="1">
</table>
<table id="2">
</table>
EOT;

$id = 3;

// Parse html
$doc = new DOMDocument();
$doc->loadHTML($html);

// Alternatively you can load from a file
// $doc->loadHTMLFile($filename);

// Find the ID
$xpath = new DOMXPath($doc);
$table = $xpath->query("//*[@id='" . $id . "']")->item(0);

echo "Found: " . ($table ? 'yes' : 'no');
于 2013-10-22T17:52:50.680 回答
1

您正在使用 mode 打开文件'a+''a'表示append ,因此它将指针放在文件的末尾。

如果你想读取文件,你可能想从头开始,所以使用模式'r'(或'r+')。 查看手册了解不同的文件模式:http ://www.php.net/manual/en/function.fopen.php

还有,fgets($file). "<br>" === '<table id="0">'永远不会是真的!您正在附加<br>到字符串,然后将其与<table id="0">期望它匹配进行比较。

$file = fopen("config.xml", "r");
while (!feof($file)){
    $line = fgets($file);
    if($line === '<table id="0">'){
        echo $line. "<br>";
    }
}
fclose($file);
于 2013-10-22T17:45:20.413 回答