PHP xpath() 函數

定義和用法

xpath() 函數運行對 XML 文檔的 XPath 查詢。

如果成功,則返回包含 SimpleXMLElement 對象的一個數組。如果失敗,則返回 false。

語法

class SimpleXMLElement
{
string xpath(path)
}
參數 描述
path 必需。XPath 路徑。

實例

XML 文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

PHP 代碼:

<?php
$xml = simplexml_load_file("test.xml");
$result = $xml->xpath("from");
print_r($result);
?>

輸出:

Array
(
[0] => SimpleXMLElement Object
  (
  [0] => John
  )
)