访问php函数内的XML节点

时间:2015-06-23 05:11:02

标签: php xml simplexml

我试图使用SimpleXML xpath()函数从XML文件中提取。我注册了一个新的命名空间,它运行得很好。

$data  = simplexml_load_string('sample.xml');
$data->registerXPathNamespace("a", "http://ns.hr-xml.org/2007-04-15");
$education = $data->xpath("//a:Education"); 
$this->saveEducationData($education);

问题是我如何访问函数内的XML节点?以下代码不起作用。应该再次注册命名空间吗?

function saveEducationData($data = ''){
  $school =  $data->xpath('/a:Institution');
}

任何帮助都将受到高度赞赏。

示例xml数据

<?xml version="1.0" encoding="utf-8"?>
<Resume xmlns="http://ns.hr-xml.org/2007-04-15" xmlns:bgt="http://wsi.com/wsinamespace" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<SResume>
<Education>
<School>
<SchoolName>Jane Institute of Technology</SchoolName>
<Address>
<Country>USA</Country>
<Region>NY</Region>
</Address>
<Degree>
<Name>MS</Name>
<StartDate>
<StringDate>2007-09-01</StringDate>
</StartDate>
<EndDate>
<StringDate>2010-05-01</StringDate>
</EndDate>
</School>
<School>
<SchoolName>Cochin Universityy</SchoolName>
<Address>
<Country>IN</Country>
<Region>COC</Region>
</Address>
<Degree>
<Name>BTech in computer science</Name>
<StartDate>
<StringDate>2005-04-10</StringDate>
</StartDate>
<EndDate>
<StringDate>2009-01-10</StringDate>
</EndDate>
</School>
<School>
<SchoolName>Indian institute of Geographic studies</SchoolName>
<Address>
<Country>IN</Country>
<Region>ALP</Region>
</Address>
<Degree>
<Name>DIploma in cartography </Name>
<StartDate>
<StringDate>2002-08-18</StringDate>
</StartDate>
<EndDate>
<StringDate>2005-01-08</StringDate>
</EndDate>
</School>
</Education>
</SResume>
</Resume>

此致 Tismon Varghese。

1 个答案:

答案 0 :(得分:0)

您可以使用DOMDocument读取XML:

$doc = new DOMDocument();
$doc->loadXML($xmlstr);

$elements = $doc->getElementsByTagName("Education");
$value = $elements->item(0)->nodeValue;

var_dump($value);

其中$ xmlstr是您的XML字符串。

要读取该值,您只需将元素传递给要提取值的函数。