dongwupu5991 2015-09-03 04:23
浏览 50

遍历simplexml_load_file并通过cURL发送每个元素节点

In my test.xml file I have multiple Field nodes like this:

<?xml version="1.0" encoding="iso-8859-1"?>
<Fields>
  <Field>
    <ID>01258</ID>
    <Name>abc</Name>
    <Contact>Contact One</Contact>
  </Field>
  <Field>
    <ID>52458</ID>
    <Name>def</Name>
    <Contact>Contact Two</Contact>
  </Field>
  <Field>
    <ID>74287</ID>
    <Name>xyz</Name>
    <Contact>Contact Three</Contact>
  </Field>
</Fields>

I would like to send each Field node one at a time through cURL to an API. This is what I have done in my PHP:

<?php
$inputFilename = 'test.xml';
$url = 'http://api-url......' // API URL

$xml = simplexml_load_file($inputFilename);
foreach($xml->Field as $field) {
  $input_xml = '<Field>'.$field.'</Field>';

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $input_xml);
  curl_setopt($ch, CURLOPT_TIMEOUT, 50);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
}

Now I have a problem. $input_xml does not seem to hold the correct xml. When I run this code, I get this error:

XML Parsing Error: junk after document element
.....
Line Number 10, Column 8:   
        </Field><Field>
  --------------^

How do I fix this? How do I make sure $field is actually outputting an xml?

  • 写回答

1条回答 默认 最新

  • doukanxi4246 2015-09-03 07:08
    关注

    Try to use DOMXPath which can correctly find all your field

    $doc = new DOMDocument("1.0", "utf-8");
    $doc->loadXML(file_get_contents($inputFilename));
    
    $xpath = new DOMXPath($doc);
    $field = $xpath->query("/fields/field");
    foreach ($fields as $field)
      {
         $field->ownerDocument;
      }
    

    You even don't use simplexml_load_file and $input_xml = '<Field>'.$field.'</Field>';

    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助