在我的test.xml文件中,我有多个Field
节点,如下所示:
<?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>
我想通过cURL一次一个地向每个Field
节点发送一个API。这就是我在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);
}
现在我遇到了问题。 $input_xml
似乎没有正确的xml。当我运行此代码时,我收到此错误:
XML Parsing Error: junk after document element
.....
Line Number 10, Column 8:
</Field><Field>
--------------^
我该如何解决这个问题?如何确保$field
实际输出xml?
答案 0 :(得分:0)
尝试使用可以正确查找所有字段的DOMXPath
$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;
}
您甚至不使用simplexml_load_file和$input_xml = '<Field>'.$field.'</Field>';