xpath查询DOMNodeList对象([length] => 0)

时间:2018-06-26 11:10:25

标签: php xml dom

我想选择具有特定属性值的元素。这是我的xml代码的示例:

    <response>
<result name="response" numFound="1171" start="0" maxScore="1.0">
<doc>
<float name="score">1.0</float>
<arr name="bm_field_candidat_valid_indexing">
<bool>false</bool>
</arr>
<str name="content">
Etudiant, jeune diplômé Informatique, nouvelles technologies Bac+5 
</str>
<arr name="sm_field_candidat_telephone">
<str>0336548651</str>
</arr>
<arr name="sm_field_candidat_ville">
<str>madrid</str>
</arr>
<arr name="sm_field_profil_candidat_compete">
<str>
Logiciel(s) bureautique: Base de données (type Access...), Présentation (type Powerpoint...), Tableur (type Excel...), Traitement de texte (type Word...) | Langage(s) de programmation: C/C++, Delphi(5/6), VB(5/6), C++builder, Java, SQL, Merise, ASP | Logiciel(s): Dreamweaver
</str>
</arr>
<arr name="sm_vid_Career_levels">
<str>Etudiant, jeune diplômé</str>
</arr>
<arr name="sm_vid_Countries">
<str>Maroc</str>
<str>Liste non ordonnée</str>
</arr>
<arr name="sm_vid_Education_levels">
<str>Bac+5 et plus</str>
</arr>
<arr name="sm_vid_Languages">
<str>maternelle</str>
</arr>
<str name="ss_name_formatted">evinalio</str>
<str name="teaser">
Etudiant, jeune diplômé americaine Mr fant rue de Libourne  » Informatique, nouvelles technologies  
</str>
<arr name="tm_vid_13_names">
<str>maternelle arabe</str>
</arr>
</doc>
</result>
</response>

我想获取由属性名称定义的值,这是我的代码:

 $url = "http://192.168.164.237:nOther=&hl.fl=";
  $xml = simplexml_load_file($url);
  $string = $xml->asXML();
  $res = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
  $res = $res->xpath('//doc');

  $dom = new DOMDocument();
  $dom->preserveWhiteSpace = false;
  $dom->loadXml($res);
  $dom->saveXML();

  $xPath = new DOMXPath($dom); 
  $storeNodes = $xPath->query( '//arr[@name="sm_field_profil_candidat_compete"]');
  print_r($storeNodes);

这就是我得到的:

  

DOMNodeList对象([length] => 0)

1 个答案:

答案 0 :(得分:0)

您不能将SimpleXMLElement数组作为XML字符串加载。使用dom_import_simplexml()

$docElement = $res->xpath('//doc')[0];
$docNode = dom_import_simplexml($docNode);
$domDocument = $docNode->ownerDocument();
$xpath = new DOMXpath($domDocument);

但是这里根本不需要将响应加载到SimpleXML中:

$xml = file_get_contents($url);
$document = new DOMDocument();
$document->preserveWhiteSpace = false;
$document->loadXml($xml);
$xpath = new DOMXpath($document); 

$storeNodes = $xpath->query(
  '//doc//arr[@name="sm_field_profil_candidat_compete"]'
);
var_dump($storeNodes);

输出:

object(DOMNodeList)#4 (1) {
  ["length"]=>
  int(1)
}

如果您有多个doc元素,则可以先获取它们,并将它们用作第二个表达式的上下文:

foreach ($xpath->query('//doc') as $docNode) {
  $storeNodes = $xpath->query(
    './/arr[@name="sm_field_profil_candidat_compete"]', $docNode
  );
  var_dump($storeNodes);
}