提取部分Xml文档&在PHP中将其转换为Json

时间:2016-02-29 04:12:04

标签: php json xml

我只需要保存以下Xml文档的一部分,然后将其转换为Json - 这是带有" row"的节点。其中的数据。

<?xml version="1.0" encoding="utf-8"?>
  <report>
     <table>
      <row device="Mobile devices with full browsers" cost="3940000" avgPosition="2.0" avgCPC="3940000" ctr="100.00%" clicks="1" impressions="1" convertedClicks="0" searchTerm="purple jeep near elgin for sale" keyword="jeepdealership" campaignState="enabled" adGroupID="7751248218" campaign="Zeigler CDJ_Dealer Campaign" campaignID="134270778"/>
      <row device="Mobile devices with full browsers" cost="3930000" avgPosition="1.0" avgCPC="3930000" ctr="100.00%" clicks="1" impressions="1" convertedClicks="0" searchTerm="jeep wrangler rubicon 2015" keyword="jeepdealership" campaignState="enabled" adGroupID="7751248218" campaign="Zeigler CDJ_Dealer Campaign" campaignID="134270778"/>
      <row device="Mobile devices with full browsers" cost="2010000" avgPosition="3.0" avgCPC="2010000" ctr="100.00%" clicks="1" impressions="1" convertedClicks="0" searchTerm="altitute jeep cherokee" keyword="2015 jeep Cherokee" campaignState="enabled" adGroupID="18188246418" campaign="Zeigler CDJ_Targeted Campaign" campaignID="134270898"/>
      <row device="Mobile devices with full browsers" cost="3990000" avgPosition="1.0" avgCPC="3990000" ctr="100.00%" clicks="1" impressions="1" convertedClicks="0" searchTerm="2012 jeep cherokee" keyword="2015 +Jeep +cherokee" campaignState="enabled" adGroupID="18188246418" campaign="Zeigler CDJ_Targeted Campaign" campaignID="134270898"/>
    </table>

这是我的代码:

$doc = new DOMDocument;
$doc->load('report.xml');
$node = $doc->documentElement;
$subnodes = $node->getElementsByTagName('row');
$json = json_encode($node->saveXML($subnodes));

这里我试图提取具有&#34; row&#34;的Xml节点,然后将其转换为Json。

我得到的错误如下:

Fatal error: Call to undefined method DOMElement::saveXML() in C:\PHP 
\Optima\adwords-examples-and-lib-8.1.0\examples\AdWords\v201601\Reporting
\DownloadCriteriaReportWithAwql.php on line 130

任何方向都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

$xml = simplexml_load_file('report.xml');
$json = json_decode(json_encode($xml->table))->row;

这将为您提供一个行数组,其中每行数据都存储在json对象中。